Mailchain is the communication layer for web3. It makes it possible for people to communicate in a crypto-native way. The platform consists of two parts:Mailchain 是 web3 的通信层。它使人们有可能以加密原生的方式进行交流。该平台由两部分组成:
An open source, multi-chain protocol for sending encrypted messages between blockchain wallet addresses.一种开源的多链协议,用于在区块链钱包地址之间发送加密消息。
A simple, unified inbox application that makes it easy for users to view and send messages using the protocol and to keep track of their on-chain activity. It's just like using email.一个简单、统一的收件箱应用程序,使用户可以使用该协议轻松查看和发送消息,并跟踪他们的链上活动。这就像使用电子邮件一样。
People often need to communicate in the context of their wallet or blockchain identity. Communication may be related to their transaction history, web3 activity or some type of important notification.人们通常需要在他们的钱包或区块链身份的背景下进行交流。通信可能与他们的交易历史、web3 活动或某种类型的重要通知有关。
Use cases include trade receipts, transaction confirmations, peer-to-peer social messages, community updates, and other onchain events.用例包括交易收据、交易确认、点对点社交消息、社区更新和其他链上事件。
Web3 provides no standard way to handle communication. Some applications work around the problem by asking users to link another method of contact (e.g. email address, phone number etc.) to an application. This compromises privacy by asking users to link or reveal an identity. Keeping track of valuable, relevant information, such as NFT mints, DeFi positions, and DAO votes across these channels can become overwhelming, confusing, and pose a privacy risk.Web3 没有提供处理通信的标准方式。一些应用程序通过要求用户将另一种联系方式(例如电子邮件地址、电话号码等)链接到应用程序来解决这个问题。这会要求用户链接或透露身份,从而损害隐私。通过这些渠道跟踪有价值的相关信息,例如 NFT 铸币厂、DeFi 头寸和 DAO 投票,可能会让人不知所措、令人困惑,并构成隐私风险。
Visit Getting Started to learn how to use the Mailchain application and start sending and receiving messages.访问入门以了解如何使用 Mailchain 应用程序并开始发送和接收消息。
Your Mailchain account is your new identity.您的 Mailchain 帐户是您的新身份。
You can use it for messaging other Mailchain users or any blockchain addresses. Your identity is yours. Nobody, not even Mailchain has access to it. When you create a Mailchain account, two things happen:您可以使用它向其他 Mailchain 用户或任何区块链地址发送消息。你的身份是你的。没有人,甚至 Mailchain 都无法访问它。当您创建 Mailchain 帐户时,会发生两件事:
The Mailchain username that you choose is registered to your identity (which is linked to your Secret Recovery Phrase).您选择的 Mailchain 用户名已注册到您的身份(与您的秘密助记词相关联)。
You create a safe space to keep your messages, registered addresses, labels, and other application data.您创建一个安全空间来保存您的消息、注册地址、标签和其他应用程序数据。
Your Secret Recovery Phrase is a collection of words that can be used to access your Mailchain identity.Your Secret Recovery Phrase 是一组单词,可用于访问您的 Mailchain 身份。
If you lose this, you may not be able to recover your account (see "What happens if I forget or lose my Secret Recovery Phrase?" below). Store a copy of it somewhere safe (for example a password manager or written down and locked away).如果您丢失了它,您可能无法恢复您的帐户(请参阅下面的“如果我忘记或丢失我的秘密恢复短语会怎样?”)。将它的副本存储在安全的地方(例如密码管理器或写下来并锁起来)。
Your data is encrypted with a key derived from your Secret Recovery Phrase. This key never leaves your browser unencrypted. Your password is used to encrypt this key, which is stored on Mailchain's server. When you choose a password, it should be a very strong password or passphrase. You should store a copy of it somewhere safe (for example a password manager or written down and locked away).您的数据使用从您的秘密恢复短语派生的密钥加密。此密钥永远不会让您的浏览器处于未加密状态。您的密码用于加密此密钥,该密钥存储在 Mailchain 的服务器上。当您选择密码时,它应该是一个非常强的密码或密码。您应该将它的副本存储在安全的地方(例如密码管理器或记下来并锁起来)。
What happens if I forget or lose my password?如果我忘记或丢失密码怎么办?
If you forget or lose your password, you can recover your account using your Secret Recovery Phrase.如果您忘记或丢失了密码,您可以使用您的秘密恢复短语恢复您的帐户。
What happens if I forget or lose my Secret Recovery Phrase?如果我忘记或丢失了我的秘密助记词怎么办?
If you forget or lose your Secret Recovery Phrase, you can recover your account if you know your Mailchain username and password.如果您忘记或丢失了您的 Secret Recovery Phrase,如果您知道您的 Mailchain 用户名和密码,则可以恢复您的帐户。
What happens if I forget my Secret Recovery Phrase and my password?如果我忘记了我的秘密助记词和密码会怎样?
If you forget your Secret Recovery Phrase and your password, your account will be inaccessible.如果您忘记了您的秘密恢复短语和密码,您的帐户将无法访问。
Will my data be accessible after I have recovered my account?恢复帐户后我的数据可以访问吗?
When you log in to Mailchain with your Secret Recovery Phrase or username and password combination, your messages, registered wallets, settings, etc. will be accessible to you.当您使用您的秘密恢复短语或用户名和密码组合登录 Mailchain 时,您将可以访问您的消息、注册的钱包、设置等。
What should I do if I suspect my Secret Recovery Phrase or username and password combination have been compromised?如果我怀疑我的秘密助记词或用户名和密码组合已被泄露,我该怎么办?
Any user who suspects their Secret Recovery Phrase or username and password combination has been compromised should create a new account and migrate their blockchain addresses by re-registering them with the new account. Any new messages will now use the messaging keys for the new account.任何怀疑其 Secret Recovery Phrase 或用户名和密码组合已被泄露的用户都应创建一个新帐户并通过使用新帐户重新注册来迁移其区块链地址。任何新消息现在都将使用新帐户的消息密钥。
Mailchain gives you the ability to check for messages sent to any of your blockchain addresses through your unified inbox. Once you register your blockchain address, you can start sending and receiving messages via that address.Mailchain 使您能够检查通过统一收件箱发送到任何区块链地址的消息。一旦你注册了你的区块链地址,你就可以开始通过该地址发送和接收消息。
Use cases include receiving notifications and communications based on your on-chain activities. You can also send messages from that address, and recipients can verify that the message originated from that address.用例包括根据您的链上活动接收通知和通信。您还可以从该地址发送邮件,收件人可以验证邮件是否来自该地址。
Your Mailchain account has an identity key, which is used to generate messaging keys. When you register an existing blockchain wallet address, you prove that you own it by signing a message of confirmation.您的 Mailchain 帐户有一个身份密钥,用于生成消息传递密钥。当您注册一个现有的区块链钱包地址时,您通过签署确认消息来证明您拥有它。
This generates a verifiable proof without requiring a blockchain transaction or gas fee. It can then be associated with a messaging key.这会生成可验证的证明,而无需区块链交易或汽油费。然后它可以与消息传递密钥相关联。
When someone sends a message to your address, the application looks up your address at the registry lookup and receives a response containing the corresponding messaging key for your address.当有人向您的地址发送消息时,应用程序会在注册表查找中查找您的地址,并收到包含您地址的相应消息密钥的响应。
Bob wants to send a message to Alice to let her know he has a new art collection coming out. He only knows the ethereum address she used when she bought his last piece. Alice has registered her ethereum address in Mailchain by signing a message confirming ownership with her wallet. Bob sends a message to Alice's address. In the background, the Mailchain application looks up Alice's address and gets the corresponding messaging key. The message is encrypted and routed using the messaging key details.Bob 想给 Alice 发送一条消息,让她知道他有一个新的艺术收藏即将出版。他只知道她买他最后一块时用的以太坊地址。爱丽丝通过用她的钱包签署确认所有权的消息,在 Mailchain 中注册了她的以太坊地址。 Bob 向 Alice 的地址发送消息。在后台,Mailchain 应用程序查找 Alice 的地址并获取相应的消息传递密钥。使用消息传递密钥详细信息对消息进行加密和路由。
When Alice opens her inbox, she can see a message from Bob sent to her ethereum address. Alice's identity and message key details are used by the application to obtain and decrypt the message body, but the private key information is never revealed.当 Alice 打开她的收件箱时,她可以看到 Bob 发送到她的以太坊地址的消息。应用程序使用 Alice 的身份和消息密钥详细信息来获取和解密消息正文,但私钥信息永远不会泄露。
Bob has no way of knowing Alice has linked any other address to her Mailchain unified inbox.Bob 无法知道 Alice 已将任何其他地址链接到她的 Mailchain 统一收件箱。
When Bob receives a reply from Alice, he can check that the message key details are valid without knowing anything else about Alice's identity.
Alice never had to enter any sensitive information to Mailchain, and she retains full control and ownership of her private keys for encryption and decryption.当 Bob 收到 Alice 的回复时,他可以在不知道 Alice 身份的任何其他信息的情况下检查消息密钥详细信息是否有效。 Alice 无需向 Mailchain 输入任何敏感信息,并且她保留对加密和解密私钥的完全控制权和所有权。
Protecting Mailchain users is a priority for us. The decision to reserve usernames was taken to increase security and increase the chance in a fair way for community members to create an account with their preferred username. Mailchain usernames are non-transferable. They cannot be sold or traded so there is no benefit for someone to seize a collection of usernames for them to go unused.保护 Mailchain 用户是我们的首要任务。保留用户名的决定是为了提高安全性,并增加社区成员以公平的方式使用他们喜欢的用户名创建帐户的机会。 Mailchain 用户名不可转让。它们不能出售或交易,因此没有任何人可以获取一组用户名以供其闲置。
Usernames in Mailchain are non-transferrable. Once a username has been taken, it cannot be reused.Mailchain 中的用户名不可转让。用户名一旦被使用,就不能再使用。
DO NOT buy or accept a username from anyone. Once you create a Secret Recovery Phrase for an account, it cannot be changed. The original owner will always know the Secret Recovery Phrase associated with that Mailchain identity and can access its account data.不要购买或接受任何人的用户名。为帐户创建秘密恢复短语后,便无法更改。原始所有者将始终知道与该 Mailchain 身份关联的秘密恢复短语,并且可以访问其帐户数据。
How can I tell if a username is reserved?如何判断用户名是否已保留?
Type the username into the 'Username' field在“用户名”字段中输入用户名
If the username is reserved, the field will turn red and display the text:如果用户名已保留,该字段将变为红色并显示文本:
This username is reserved, contact support@mailchain if you want to claim it.此用户名已保留,如果您想申请,请联系 support@mailchain。
Alternatively, if the username is taken, the text will read:或者,如果用户名已被占用,文本将显示为:
This username is taken. Try another.该用户名已被使用。尝试另一个。
Or, if the username is unavailable for security reasons (e.g. admin@) the text will read:或者,如果出于安全原因用户名不可用(例如 admin@),文本将显示为:
This username is unavailable. Try another.此用户名不可用。尝试另一个。
How can I request a reserved username?我如何申请保留的用户名?
If you would like to claim a reserved username, please raise a support request with details of the name you would like to register. If you represent a web3 project please provide details or justification.如果您想申请保留的用户名,请提出支持请求,并提供您想要注册的名称的详细信息。如果您代表 web3 项目,请提供详细信息或理由。
Mailchain gives you complete ownership of your data. We’ve built Mailchain around the principle that only you should be able to view your private data.Mailchain 为您提供对数据的完全所有权。我们围绕只有您才能查看您的私人数据的原则构建了 Mailchain。
All Mailchain messages are encrypted end-to-end by default. To achieve complete end-to-end encryption, your private keys are never revealed to the Mailchain protocol. Your Secret Recovery Phrase is used to create a series a private keys that each perform independent actions which allow you to privately, register addresses, authenticate, store and save messages.默认情况下,所有 Mailchain 消息都是端到端加密的。为了实现完整的端到端加密,您的私钥永远不会透露给 Mailchain 协议。您的秘密恢复短语用于创建一系列私钥,每个私钥执行独立的操作,允许您私下注册地址、验证、存储和保存消息。
The Mailchain application encrypts your data in your browser before storing it with Mailchain, meaning only you can decrypt it. Mailchain cannot decrypt your data. This includes your Secret Recovery Phrase, messages, and registered addresses.Mailchain 应用程序会先在您的浏览器中加密您的数据,然后再使用 Mailchain 存储数据,这意味着只有您可以解密它。 Mailchain 无法解密您的数据。这包括您的秘密恢复短语、消息和注册地址。
After you successfully authenticate with your username and password, a key that is known only to you, is used to encrypt your Secret Recovery Phrase. Your password is never sent to Mailchain in any form. This also means we have no way recover your account if you lose your password or are unable to complete any other account recovery options.在您成功使用您的用户名和密码进行身份验证后,将使用一个只有您知道的密钥来加密您的 Secret Recovery Phrase。您的密码绝不会以任何形式发送到 Mailchain。这也意味着如果您丢失密码或无法完成任何其他帐户恢复选项,我们将无法恢复您的帐户。
Please see FAQs for more information on account recovery.有关帐户恢复的更多信息,请参阅常见问题解答。
Mailchain uses a messaging key in place of your wallet key to encrypt and decrypt messages for each address. Messaging keys are more secure for encryption and mean you don’t expose your wallet’s private key.Mailchain 使用消息传递密钥代替您的钱包密钥来加密和解密每个地址的消息。消息密钥加密更安全,这意味着您不会暴露钱包的私钥。
When you register a wallet address with your Mailchain account, a new messaging key is generated. With your wallet, you sign a confirmation to indicate this key should be used for messaging. Signing this confirmation creates a proof that users can independently verify. The messaging private key is known only to you.当您使用 Mailchain 帐户注册钱包地址时,会生成一个新的消息传递密钥。使用您的钱包,您签署确认以指示此密钥应用于消息传递。签署此确认书可创建用户可以独立验证的证明。消息私钥只有您知道。
Registered addresses are encrypted before being stored, and you only need to verify ownership of your wallet address once. Mailchain disconnects your wallet after your wallet has created the proof. Your wallet private key is never exposed.注册地址在存储前进行加密,您只需验证一次钱包地址的所有权。在您的钱包创建证明后,Mailchain 会断开您的钱包。您的钱包私钥永远不会暴露。
Each time a message is sent via Mailchain, a new encryption key is created to encrypt the message contents and its location. This encryption key is then encrypted uniquely for each address that is receiving the message. A new key is created for each recipient and for each new message.每次通过 Mailchain 发送消息时,都会创建一个新的加密密钥来加密消息内容及其位置。然后,该加密密钥会针对接收消息的每个地址进行唯一加密。为每个收件人和每个新消息创建一个新密钥。
Only the intended recipient(s) can recover the key then decrypt the location and message contents. All information within or about your messages, for example, sender, subject or date, is encrypted. Mailchain cannot read your messages, the storage provider cannot read your messages, your internet service provider cannot read your messages.只有预期的收件人才能恢复密钥,然后解密位置和消息内容。您的邮件中或关于您的邮件的所有信息,例如发件人、主题或日期,均已加密。 Mailchain 无法读取您的消息,存储提供商无法读取您的消息,您的互联网服务提供商无法读取您的消息。
When a message is sent, the message is encrypted and stored on distributed storage. An encrypted "delivery request" holds information for the message recipient to be able to collect their encrypted message. Messages are held in an ephemeral transport layer until the message has been retrieved by all the recipients or until it expires.发送消息时,消息会被加密并存储在分布式存储中。加密的“传递请求”包含消息接收者能够收集其加密消息的信息。消息保存在临时传输层中,直到消息被所有收件人检索或直到消息过期。
The Mailchain app will continuously check for new messages. Once a new message has been found, it is saved in your private inbox. Before being stored, messages are re-encrypted with a key that is specific to your inbox.Mailchain 应用程序将持续检查新消息。找到新消息后,它会保存在您的私人收件箱中。在存储之前,邮件会使用收件箱特定的密钥重新加密。
Your inbox is designed to be intuitive and can be filtered in a familiar way but, it is secured so that only you can see and understand the relationships between your addresses and content. All IDs, filters and metadata are hashed or encrypted with a key derived from your private messaging key. Mailchain’s database cannot identify any relationships even if multiple addresses received the same messages; all the IDs, filters and content look completely different.您的收件箱设计直观,可以以熟悉的方式进行过滤,但它是安全的,因此只有您可以看到和理解您的地址和内容之间的关系。所有 ID、过滤器和元数据都使用从您的私人消息密钥派生的密钥进行散列或加密。即使多个地址收到相同的消息,Mailchain 的数据库也无法识别任何关系;所有的 ID、过滤器和内容看起来都完全不同。
Mailchain reserved some brand names and names under 5 characters long. For more information, see reserved names below.Mailchain 保留了一些品牌名称和长度在 5 个字符以下的名称。有关详细信息,请参阅下面的保留名称。
Choose a very strong password or passphrase.选择一个非常强的密码或密码。
caution警告
You cannot reset your Mailchain password and if you lose it, you will need to restore your Mailchain identity using your Secret Recovery Phrase.您无法重置您的 Mailchain 密码,如果您丢失了它,您将需要使用您的 Secret Recovery Phrase 恢复您的 Mailchain 身份。
Please add your username and password to a password manager or write it down and store it somewhere safe. See Understanding Mailchain Authentication for more information.请将您的用户名和密码添加到密码管理器或将其写下来并存放在安全的地方。有关详细信息,请参阅了解邮件链身份验证。
Take a moment to expand the 'Show advanced options' section and store your Secret Recovery Phrase.花点时间展开“显示高级选项”部分并存储您的秘密助记词。
tip提示
Please add your Secret Recovery Phrase to a password manager or write it down and store it somewhere safe. Losing this could mean you lose access to your Mailchain identity forever, so please store it somewhere safe.请将您的 Secret Recovery Phrase 添加到密码管理器或将其写下来并存放在安全的地方。丢失它可能意味着您永远无法访问您的 Mailchain 身份,因此请将其存储在安全的地方。
Check the checkbox, assuming you have stored your password safely.假设您已安全存储密码,请选中该复选框。
Review the terms of service and privacy policy to ensure you are comfortable with what we offer, and how we do it.查看服务条款和隐私政策,以确保您对我们提供的服务以及我们的工作方式感到满意。
Pass the hCaptcha check to prove you are human.通过 hCaptcha 检查以证明您是人类。
Click 'Continue'.单击“继续”。
Next, you will be asked if you would like to download your Secret Recovery Phrase. If you did not follow previous warnings to write down and store the phrase, please ensure you select 'Download' and store the file securely so that others do not have access to it. Otherwise you can skip this step.接下来,系统会询问您是否要下载您的 Secret Recovery Phrase。如果您没有按照之前的警告写下并存储该短语,请确保您选择“下载”并安全地存储文件,以免其他人访问它。否则你可以跳过这一步。
Mailchain reserved some usernames for known web3 projects and names under 5 characters.
Please see Reserved Usernames for more information.Mailchain 为已知的 web3 项目保留了一些用户名和 5 个字符以下的名称。有关详细信息,请参阅保留的用户名。
If you have an existing blockchain wallet, you can register the wallet to receive messages sent to that address. Visit connecting and registering wallets for more information.如果您有现有的区块链钱包,您可以注册钱包以接收发送到该地址的消息。访问连接和注册钱包了解更多信息。
Follow these steps to connect and register an existing blockchain wallet address:请按照以下步骤连接并注册现有的区块链钱包地址:
Click a button to open the connect wallet modal:单击一个按钮打开连接钱包模式:
Select a wallet provider (e.g. Metamask), then click 'Connect'选择钱包提供商(例如 Metamask),然后单击“连接”
Choose the address to connect, then click Next.选择要连接的地址,然后单击下一步。
Click 'Connect' to confirm Mailchain should be able to read your address.单击“连接”以确认 Mailchain 应该能够读取您的地址。
The address is now connected, but we need to register it in Mailchain. To do this:该地址现已连接,但我们需要在 Mailchain 中注册它。去做这个:
Click 'Verify Address'点击“验证地址”
A 'Signature Request' will appear in your wallet. It contains the following text:“签名请求”将出现在您的钱包中。它包含以下文本:
Message: 信息:
Welcome to Mailchain! 欢迎来到邮链!
Please sign to start using this address with Mailchain. This will not trigger a blockchain transaction or cost any gas fees. 请签名以开始将此地址与 Mailchain 一起使用。这不会触发区块链交易或花费任何汽油费。
What's happening? 发生了什么?
A messaging key will be registered with this address and used only for messaging. It will replace any existing registered messaging keys. 消息密钥将使用该地址注册并仅用于消息传递。它将替换任何现有的注册消息密钥。
Mailchain will check if you have any Web3 domain name services (e.g. ENS or Unstoppable Domains).Mailchain 将检查您是否有任何 Web3 域名服务(例如 ENS 或 Unstoppable Domains)。 For more information on configuring domain name services, please see Web3 Domain Name Guides.有关配置域名服务的更多信息,请参阅 Web3 域名指南。
You can optionally label your address to give it a friendly name and make your Inbox folders easier to manage.您可以选择标记您的地址,为其提供一个友好的名称,并使您的收件箱文件夹更易于管理。
Click 'Apply' to save your changes.单击“应用”以保存您的更改。
By default, Mailchain is able to receive messages for your existing blockchain wallet address before you sign up. Click 'Synchronize' to get these messages, or click 'Skip' to synchronize later.默认情况下,Mailchain 能够在您注册之前接收您现有区块链钱包地址的消息。单击“同步”以获取这些消息,或单击“跳过”以稍后同步。
You can now click 'Done' to disconnect your wallet and close the modal, or choose to register another address.您现在可以单击“完成”以断开您的钱包并关闭模式,或选择注册另一个地址。
You will be able to see a folder in the sidebar for your registered address. To manage the address, click on 'Settings'.您将能够在边栏中看到一个文件夹,用于您的注册地址。要管理地址,请单击“设置”。
When you compose a message, you can select the address to send from in the message dropdown.撰写消息时,您可以在消息下拉列表中选择要发送的地址。
Log into your Mailchain account. (Follow this guide to create an account)登录您的 Mailchain 帐户。 (按照本指南创建一个帐户)
Click 'Compose' in the sidebar, and fill out the following fields:单击边栏中的“撰写”,然后填写以下字段:
To is the intended recipient in any of the following formats:To 是以下任何格式的预期收件人:
Identity Type身份类型
Address Format地址格式
Example例子
Mailchain邮件链
username@mailchain用户名@邮件链
alice@mailchain爱丽丝@mailchain
Ethereum以太坊
address@ethereum地址@ethereum
0x123456789@ethereum0x123456789@ethereum
More protocols coming soon更多协议即将推出
note笔记
If you send a message to an Ethereum address that has not yet signed up, the message will be retained for up to six months. It will be delivered to owner when they register the address with Mailchain.如果您向尚未注册的以太坊地址发送消息,该消息将最多保留六个月。当他们在 Mailchain 注册地址时,它将被交付给所有者。
From is the address you are sending from. It will be your Mailchain address or any registered address.From 是您发送的地址。这将是您的 Mailchain 地址或任何注册地址。
Fill out the Subject and the message body, then click Send.填写主题和消息正文,然后单击发送。
When your message is sent, a confirmation box will pop up. You can view it in the "Sent" folder.发送消息时,将弹出一个确认框。您可以在“已发送”文件夹中查看它。
Log into your Mailchain account (or follow this guide to create an account).登录您的 Mailchain 帐户(或按照本指南创建一个帐户)。
If you have not yet connected a wallet address, click 'Inbox' to view your messages.如果您还没有连接钱包地址,请点击“收件箱”查看您的消息。
If you have registered wallet addresses, you can view all your messages in 'All Inboxes'. To view the messages sent to a specific address select the corresponding inbox.如果您已经注册了钱包地址,您可以在“所有收件箱”中查看您的所有消息。要查看发送到特定地址的消息,请选择相应的收件箱。
Each inbox displays the number of unread messages. When you select the inbox, any unread messages will have a blue dot next to them.每个收件箱都会显示未读邮件的数量。当您选择收件箱时,任何未读邮件旁边都会有一个蓝点。
You can mark messages as read or unread, or carry out other actions including star to mark as important or archive to remove them from view.您可以将消息标记为已读或未读,或执行其他操作,包括加星以标记为重要或存档以将其从视图中删除。
Mailchain users can use their .aurora domain name to send and receive messages. It’s simple to get started…Mailchain 用户可以使用他们的 .aurora 域名来发送和接收消息。上手很简单……
Introduction介绍
Aurora is an Ethereum Virtual Machine (EVM) based on the layer 1 proof-of-stake blockchain NEAR Protocol. Aurora provides a solution for developers to deploy their apps on an Ethereum-compatible platform, with low transaction costs for their users.Aurora 是基于第 1 层权益证明区块链 NEAR 协议的以太坊虚拟机 (EVM)。 Aurora 为开发人员提供了一种解决方案,可以将他们的应用程序部署在与以太坊兼容的平台上,同时降低用户的交易成本。
You can register .aurora NFT names at Freename.io, then ‘mint’ them on the Aurora blockchain. These domains give people full ownership and control of their digital identity, with no renewal fees.您可以在 Freename.io 注册 .aurora NFT 名称,然后在 Aurora 区块链上“铸造”它们。这些域名让人们可以完全拥有和控制他们的数字身份,无需续订费用。
How to add your .aurora name to Mailchain如何将您的 .aurora 名称添加到 Mailchain
Your wallet contains your .aurora name (i.e. it contains an NFT of a name you either minted or had transferred to your wallet).您的钱包包含您的 .aurora 名称(即它包含您铸造或转移到您钱包的名称的 NFT)。
You have a Mailchain account (see here)您有一个 Mailchain 帐户(请参阅此处)
Add Your .aurora Name to Mailchain将您的 .aurora 名称添加到邮件链
Log in to your Mailchain Account.登录到您的 Mailchain 帐户。
Click “Register Your Wallet”.点击“注册你的钱包”。
A modal will open. Select a wallet provider (e.g. Metamask), then click 'Connect'将打开一个模态。选择钱包提供商(例如 Metamask),然后单击“连接”
Choose the address to connect, then click Next.选择要连接的地址,然后单击下一步。
Click 'Connect' to confirm Mailchain should be able to read your address.单击“连接”以确认 Mailchain 应该能够读取您的地址。
The address is now connected, but we need to register it in Mailchain. To do this, click 'Verify Address'该地址现已连接,但我们需要在 Mailchain 中注册它。为此,请单击“验证地址”
A 'Signature Request' will appear in your wallet. It contains the following text:“签名请求”将出现在您的钱包中。它包含以下文本:
Message: Welcome to Mailchain! Please sign to start using this address with Mailchain. This will not trigger a blockchain transaction or cost any gas fees. What's happening? A messaging key will be registered with this address and used only for messaging. It will replace any existing registered messaging keys. Technical Details: Address: `your_address` Messaging key: `a_generated_messaging_key` Nonce: `a_number`
Review the request and click 'Sign' to complete verification.查看请求并单击“签名”以完成验证。
The next step checks for connected name services, including .aurora names. This example found epistola.aurora. If you do not see your name here, you can manually search for it using the search box. If it still cannot be found, please see Aurora FAQs).下一步检查连接的名称服务,包括 .aurora 名称。此示例找到了 epistola.aurora。如果您在这里没有看到您的姓名,您可以使用搜索框手动搜索。如果仍然找不到,请参阅 Aurora 常见问题解答)。
You can add a custom label for your address. By default, Mailchain will populate your .aurora name. Click Apply to save and continue.您可以为地址添加自定义标签。默认情况下,Mailchain 将填充您的 .aurora 名称。单击“应用”以保存并继续。
Mailchain is able to receive messages for your wallet address before you sign up. Click 'Synchronize' to retrieve these messages, or click 'Skip' to synchronize later. Any synchronized messages will appear in your inbox.Mailchain 能够在您注册之前接收您的钱包地址的消息。单击“同步”以检索这些消息,或单击“跳过”以稍后同步。任何同步的消息都会出现在您的收件箱中。
You can now click 'Done' to disconnect your wallet and close the modal, or choose to register another address.您现在可以单击“完成”以断开您的钱包并关闭模式,或选择注册另一个地址。
You will now see the newly added inbox on the left. This will be labelled with the label you provided when registering the address. Any messages sent to that address or the .aurora name will appear in this inbox.您现在将在左侧看到新添加的收件箱。这将标有您在注册地址时提供的标签。发送到该地址或 .aurora 名称的任何邮件都将出现在该收件箱中。
How To Send A Message Using Your .aurora Name如何使用您的 .aurora 名称发送消息
With Mailchain you can send Mailchain message from your .aurora name to other Mailchain users.使用 Mailchain,您可以从您的 .aurora 名称向其他 Mailchain 用户发送 Mailchain 消息。
Your wallet contains your .aurora name (i.e. it contains an NFT of a name you either minted or had transferred to your wallet).您的钱包包含您的 .aurora 名称(即它包含您铸造或转移到您钱包的名称的 NFT)。
You have a Mailchain account (see here)您有一个 Mailchain 帐户(请参阅此处)
You have added your .aurora name to Mailchain (see above)您已将您的 .aurora 名称添加到 Mailchain(见上文)
Compose And Send A Message From Your .aurora Name使用您的 .aurora 名称撰写并发送消息
Log into your Mailchain account.登录您的 Mailchain 帐户。
Click 'Compose' in the sidebar.单击边栏中的“撰写”。
In the New Message window, click the “From” dropdown menu.在“新消息”窗口中,单击“发件人”下拉菜单。
Select your .aurora name.选择您的 .aurora 名称。
Fill out the rest of the message, then click Send填写消息的其余部分,然后单击“发送”
Your message should be successfully sent.您的消息应该已成功发送。
Done! Your recipient will receive your message from your .aurora name.完毕!您的收件人将通过您的 .aurora 名称收到您的消息。
Frequently asked questions for working with Aurora and Mailchain.使用 Aurora 和 Mailchain 的常见问题解答。
How do I register an .aurora name?如何注册 .aurora 名称?
The .aurora registry is operated by Freename. Visit Freename.io and follow instructions on their site..aurora 注册表由 Freename 运营。访问 Freename.io 并按照其网站上的说明进行操作。
Can someone send me a Mailchain message to my Aurora address or .aurora name?有人可以向我的 Aurora 地址或 .aurora 名称发送 Mailchain 消息吗?
You can ask anyone to send messages to your .aurora name or the wallet address you use on aurora… it’s a Web3 identity after all!您可以要求任何人向您的 .aurora 名称或您在 aurora 上使用的钱包地址发送消息……毕竟这是一个 Web3 身份!
What happens when someone sends a message to my .aurora name in Mailchain?当有人向我在 Mailchain 中的 .aurora 名称发送消息时会发生什么?
When someone sends a Mailchain message to an Aurora name, Mailchain resolves the .aurora name and delivers the message to the resolved address (the address of registered owner of the .aurora NFT).当有人向 Aurora 名称发送 Mailchain 消息时,Mailchain 解析 .aurora 名称并将消息传递到解析地址(.aurora NFT 的注册所有者的地址)。
If you are the owner of the minted name, then the message will arrive in your inbox.如果您是铸造名称的所有者,则该消息将到达您的收件箱。
What if I have not yet registered my wallet address with Mailchain?如果我还没有在 Mailchain 注册我的钱包地址怎么办?
If you have not yet registered the wallet address with Mailchain, the protocol will still accept the encrypted message and store it for up to 90 days. You can synchronize messages for this address when you register the wallet address. (See How to add your .aurora name to Mailchain)如果您尚未在 Mailchain 注册钱包地址,该协议仍会接受加密消息并将其存储最多 90 天。您可以在注册钱包地址时同步该地址的消息。 (请参阅如何将您的 .aurora 名称添加到 Mailchain)
My .aurora name was not found, what should I check?找不到我的 .aurora 名称,我应该检查什么?
Check you are registering the intended wallet address检查您是否正在注册预期的钱包地址
Check your .aurora name is minted and in your wallet检查您的 .aurora 名称是否已创建并在您的钱包中
How does Mailchain resolve .aurora names?Mailchain 如何解析 .aurora 名称?
Mailchain will always resolve the name from the Freename.io resolver API so it will reflect the latest changes returned by the resolver.Mailchain 将始终从 Freename.io 解析器 API 解析名称,因此它将反映解析器返回的最新更改。
What happens if I no longer own my .aurora name?如果我不再拥有我的 .aurora 域名会怎样?
If your address is no longer the owner of the .aurora name, it will not resolve and Mailchain messages will no longer be sent to the address. If someone else registers the address that owns the name in Mailchain, they will be able to receive messages sent to the .aurora name. This will not have any impact on messages already in your inbox.如果您的地址不再是 .aurora 名称的所有者,它将无法解析并且 Mailchain 消息将不再发送到该地址。如果其他人在 Mailchain 中注册了拥有该名称的地址,他们将能够接收发送到 .aurora 名称的消息。这不会对您收件箱中已有的邮件产生任何影响。
Does Mailchain support shorthand addressing for .aurora?Mailchain 是否支持 .aurora 的速记寻址?
Mailchain users can use their ENS domain to send and receive messages. It’s simple to get started…Mailchain 用户可以使用他们的 ENS 域来发送和接收消息。上手很简单……
Introduction介绍
The Ethereum Name Service (ENS) is a distributed, open, and extensible naming system based on the Ethereum blockchain.
ENS’s job is to map human-readable names like ‘alice.eth’ to machine-readable identifiers such as Ethereum addresses, other cryptocurrency addresses, content hashes, and metadata. ENS also supports ‘reverse resolution’, making it possible to associate metadata such as canonical names or interface descriptions with Ethereum addresses. — Source: ENS DocumentationEthereum Name Service(ENS)是一个基于以太坊区块链的分布式、开放、可扩展的命名系统。 ENS 的工作是将人类可读的名称(如“alice.eth”)映射到机器可读的标识符(如以太坊地址、其他加密货币地址、内容哈希和元数据)。 ENS 还支持“反向解析”,可以将规范名称或接口描述等元数据与以太坊地址相关联。 — 来源:ENS 文档
How To Add Your ENS Name To Mailchain如何将您的 ENS 名称添加到邮件链
Log in to your Mailchain Account.登录到您的 Mailchain 帐户。
Click “Register Your Wallet”.点击“注册你的钱包”。
A modal will open. Select a wallet provider (e.g. Metamask), then click 'Connect'将打开一个模态。选择钱包提供商(例如 Metamask),然后单击“连接”
Choose the address to connect, then click Next.选择要连接的地址,然后单击下一步。
Click 'Connect' to confirm Mailchain should be able to read your address.单击“连接”以确认 Mailchain 应该能够读取您的地址。
The address is now connected, but we need to register it in Mailchain. To do this, click 'Verify Address'该地址现已连接,但我们需要在 Mailchain 中注册它。为此,请单击“验证地址”
A 'Signature Request' will appear in your wallet. It contains the following text:“签名请求”将出现在您的钱包中。它包含以下文本:
Message: Welcome to Mailchain! Please sign to start using this address with Mailchain. This will not trigger a blockchain transaction or cost any gas fees. What's happening? A messaging key will be registered with this address and used only for messaging. It will replace any existing registered messaging keys. Technical Details: Address: `your_address` Messaging key: `a_generated_messaging_key` Nonce: `a_number`
Review the request and click 'Sign' to complete verification.查看请求并单击“签名”以完成验证。
The next step checks for connected name services, including ENS names. This example found happywriter.eth. If you do not see your ENS name here, you can manually search for it using the search box. If it still cannot be found, please see ENS FAQs here.下一步检查连接的名称服务,包括 ENS 名称。这个例子找到了 happywriter.eth。如果您在这里没有看到您的 ENS 名称,您可以使用搜索框手动搜索它。如果仍然找不到,请在此处查看 ENS 常见问题解答。
You can add a custom label for your address. By default, Mailchain will populate your ENS name. Click Apply to save and continue.您可以为地址添加自定义标签。默认情况下,Mailchain 将填充您的 ENS 名称。单击“应用”以保存并继续。
Mailchain is able to receive messages for your wallet address before you sign up. Click 'Synchronize' to retrieve these messages, or click 'Skip' to synchronize later. Any synchronized messages will appear in your inbox.Mailchain 能够在您注册之前接收您的钱包地址的消息。单击“同步”以检索这些消息,或单击“跳过”以稍后同步。任何同步的消息都会出现在您的收件箱中。
You can now click 'Done' to disconnect your wallet and close the modal, or choose to register another address.您现在可以单击“完成”以断开您的钱包并关闭模式,或选择注册另一个地址。
You will now see the newly added inbox on the left. This will be labelled with the label you provided when registering the address. Any messages sent to that address or the ENS name will appear in this inbox.您现在将在左侧看到新添加的收件箱。这将标有您在注册地址时提供的标签。发送到该地址或 ENS 名称的任何消息都将显示在此收件箱中。
How To Send A Message Using Your ENS Name如何使用您的 ENS 名称发送消息
With Mailchain you can send Mailchain message from your ENS name to other Mailchain users.使用 Mailchain,您可以从您的 ENS 名称向其他 Mailchain 用户发送 Mailchain 消息。
Frequently asked questions for working with ENS and Mailchain.使用 ENS 和 Mailchain 的常见问题解答。
Can someone send me a Mailchain message to my ENS address?有人可以向我的 ENS 地址发送 Mailchain 消息吗?
You can ask anyone to send messages to your ENS name… it’s a Web3 identity afterall!您可以要求任何人向您的 ENS 名称发送消息……毕竟这是一个 Web3 身份!
What happens when someone sends a message to my ENS name in Mailchain?当有人向我在 Mailchain 中的 ENS 名称发送消息时会发生什么?
When someone sends a Mailchain message to an ENS name, Mailchain resolves the ENS name and delivers the message to the ENS Resolved Address (the registered ETH address).当有人向 ENS 名称发送 Mailchain 消息时,Mailchain 解析 ENS 名称并将消息传递到 ENS Resolved Address(注册的 ETH 地址)。
If you have already registered the wallet address, then the message will arrive in your inbox.如果您已经注册了钱包地址,那么该消息将到达您的收件箱。
What if I have not yet registered my wallet address with Mailchain?如果我还没有在 Mailchain 注册我的钱包地址怎么办?
If you have not yet registered the wallet address with Mailchain, the protocol will still accept the encrypted message and store it for up to 90 days. You can synchronise messages for this address when you register the wallet address. (See How to add your ENS name to Mailchain)如果您尚未在 Mailchain 注册钱包地址,该协议仍会接受加密消息并将其存储最多 90 天。您可以在注册钱包地址时同步该地址的消息。 (请参阅如何将您的 ENS 名称添加到邮件链)
What happens when my ENS name expires?当我的 ENS 名称过期时会发生什么?
When your ENS names expires, Mailchain messages will no longer be sent to the address. If someone else registers the name, they will be able to receive messages to this address.当您的 ENS 名称过期时,邮件链消息将不再发送到该地址。如果其他人注册了该名称,他们将能够接收到该地址的消息。
My ENS name was not found, what should I check?找不到我的 ENS 名称,我应该检查什么?
Check you are registering the intended wallet address检查您是否正在注册预期的钱包地址
Check your ENS Primary Resolver is configured to resolve your address in https://app.ens.domains检查您的 ENS 主解析器是否配置为在 https://app.ens.domains 中解析您的地址
What happens if I make a change where my ENS address resolves?如果我更改我的 ENS 地址的解析位置会怎样?
Mailchain will always resolve the underlying name from the ENS contracts so it will reflect the latest changes returned by the resolver.Mailchain 将始终解析 ENS 合约中的基础名称,因此它将反映解析器返回的最新更改。
Follow these steps to register an ENS name:请按照以下步骤注册 ENS 名称:
NOTE: You will need some ETH to purchase an ENS name. At the time of writing, >0.01ETH was required to complete this section.注意:您将需要一些 ETH 来购买 ENS 名称。在撰写本文时,完成此部分需要 >0.01ETH。
Search for an available name, then click search. (We used happywriter.eth in this guide)
The app will show you if the name is available.
Choose the length of the registration period you would like, then click “Request to Register”.
Check the transaction details, then confirm it to complete step 1.
Once the transaction is confirmed, you will need to wait for a period of 1 minute (step 2), before proceeding to step 3.
Click “Register” to proceed with the registration.
Check the transaction details, then confirm it to complete the registration.
Once successful, the app will confirm.
If you would like to use the ENS name to send messages from Mailchain, then click on “Set As Primary ENS Name” and follow the guide: Set an ENS Primary Resolver.
How Do I Set An ENS Primary Resolver?如何设置 ENS 主解析器?
An ENS Primary Resolver designates one of your ENS names to represent your Ethereum account and act as your cross-platform Web3 username and profile.ENS 主解析器指定您的一个 ENS 名称来代表您的以太坊帐户,并充当您的跨平台 Web3 用户名和个人资料。
Follow these steps to set up the ENS Primary Resolver for your ENS name:请按照以下步骤为您的 ENS 名称设置 ENS 主解析器:
If you do not have a Primary Resolver set, your screen will display the message Primary ENS Name (reverse record): not set.
To set the Primary ENS Name record, click on the drop-down and select the ENS name you want to be your Primary ENS Name.
(The example below shows happywriter.eth, and ENS subdomain has been configure to resolve to 0xc1db...89d7)

Click "Save".
Check the transaction details, then confirm it to set the record.
Once the transaction is successful, you will see the ENS name as the “Primary ENS Name (reverse record)”
You have now set your Primary ENS Name. This will start to appear in Web3 applications you connect to. You can now register the name with Mailchain to start communicating messages
Does Mailchain support shorthand addressing for ENS?Mailchain 是否支持 ENS 的速记寻址?
Getting Started With Freename Web3 DomainsFreename Web3 域名入门
Mailchain users can use their Freename Web3 domain names to send and receive messages. It’s simple to get started…Mailchain 用户可以使用他们的 Freename Web3 域名来发送和接收消息。上手很简单……
Introduction介绍
Freename (https://freename.io) is a web3 domain registrar for top-level domains (TLD) and second-level domains (SLD). Users can register and mint their own web3 TLDs and SLDs. These domains give people full ownership and control of their digital identity, with no renewal fees.Freename (https://freename.io) 是顶级域名 (TLD) 和二级域名 (SLD) 的 web3 域名注册商。用户可以注册并创建自己的 web3 TLD 和 SLD。这些域名让人们可以完全拥有和控制他们的数字身份,无需续订费用。
How To Add Your Freename Domain Name To Mailchain如何将您的 Freename 域名添加到 Mailchain
You have a Mailchain account (see here).您有一个 Mailchain 帐户(请参阅此处)。
Your wallet contains your Freename name (i.e. it contains an NFT of a name you either minted or had transferred to your wallet).您的钱包包含您的 Freename 名称(即它包含您铸造或转移到您钱包的名称的 NFT)。
The domain name should resolve to your wallet address. You can check this using https://whois.freename.io/ to check your address and name resolve correctly.
The example below uses epistola.hodl@freename.mailchain which can be shortened to epistola.hodl.域名应解析为您的钱包地址。您可以使用 https://whois.freename.io/ 检查您的地址和名称是否正确解析。下面的示例使用 epistola.hodl@freename.mailchain,它可以缩短为 epistola.hodl。
Add Your Freename Name to Mailchain将您的 Freename 名称添加到 Mailchain
Log in to your Mailchain Account.登录到您的 Mailchain 帐户。
Click “Register Your Wallet”.点击“注册你的钱包”。
A modal will open. Select a wallet provider (e.g. Metamask), then click 'Connect'将打开一个模态。选择钱包提供商(例如 Metamask),然后单击“连接”
Choose the address to connect, then click Next.选择要连接的地址,然后单击下一步。
Click 'Connect' to confirm Mailchain should be able to read your address.单击“连接”以确认 Mailchain 应该能够读取您的地址。
The address is now connected, but we need to register it in Mailchain. To do this, click 'Verify Address'该地址现已连接,但我们需要在 Mailchain 中注册它。为此,请单击“验证地址”
A 'Signature Request' will appear in your wallet. It contains the following text:“签名请求”将出现在您的钱包中。它包含以下文本:
Message: Welcome to Mailchain! Please sign to start using this address with Mailchain. This will not trigger a blockchain transaction or cost any gas fees. What's happening? A messaging key will be registered with this address and used only for messaging. It will replace any existing registered messaging keys. Technical Details: Address: `your_address` Messaging key: `a_generated_messaging_key` Nonce: `a_number`
Review the request and click 'Sign' to complete verification.查看请求并单击“签名”以完成验证。
The next step checks for connected name services, including all any Freename names. This example found epistola.hodl. If you do not see your name here, you can manually search for it using the search box. If it still cannot be found, please see Freename FAQs My Freename domain was not found, what should I check?.下一步检查连接的名称服务,包括所有任何 Freename 名称。此示例找到了 epistola.hodl。如果您在这里没有看到您的姓名,您可以使用搜索框手动搜索。如果仍然找不到,请查看 Freename FAQs 找不到我的 Freename 域,我应该检查什么?。
You can add a custom label for your address. By default, Mailchain will populate your Freename domain. Click Apply to save and continue.您可以为地址添加自定义标签。默认情况下,Mailchain 将填充您的 Freename 域。单击“应用”以保存并继续。
Mailchain is able to receive messages for your wallet address before you sign up. Click 'Synchronize' to retrieve these messages, or click 'Skip' to synchronize later. Any synchronized messages will appear in your inbox.Mailchain 能够在您注册之前接收您的钱包地址的消息。单击“同步”以检索这些消息,或单击“跳过”以稍后同步。任何同步的消息都会出现在您的收件箱中。
You can now click 'Done' to disconnect your wallet and close the modal, or choose to register another address.您现在可以单击“完成”以断开您的钱包并关闭模式,或选择注册另一个地址。
You will now see the newly added inbox on the left. This will be labelled with the label you provided when registering the address. Any messages sent to that address or the Freename name will appear in this inbox.您现在将在左侧看到新添加的收件箱。这将标有您在注册地址时提供的标签。发送到该地址或 Freename 名称的任何消息都将出现在该收件箱中。
How To Send A Message Using Your Freename Domain Name如何使用您的 Freename 域名发送消息
With Mailchain you can send a Mailchain message from your Freename domain name to other Mailchain users.使用 Mailchain,您可以从您的 Freename 域名向其他 Mailchain 用户发送 Mailchain 消息。
You have a Mailchain account (see here).您有一个 Mailchain 帐户(请参阅此处)。
Your wallet contains your Freename name (i.e. it contains an NFT of a name you either minted or had transferred to your wallet).您的钱包包含您的 Freename 名称(即它包含您铸造或转移到您钱包的名称的 NFT)。
The domain name should resolve to your wallet address. You can check this using https://whois.freename.io/ to check your address and name resolve correctly.
The example below uses epistola.hodl@freename.mailchain which can be shortened to epistola.hodl.域名应解析为您的钱包地址。您可以使用 https://whois.freename.io/ 检查您的地址和名称是否正确解析。下面的示例使用 epistola.hodl@freename.mailchain,它可以缩短为 epistola.hodl。
You have added your Freename web3 domain to Mailchain (see above)您已将您的 Freename web3 域添加到 Mailchain(见上文)
Compose And Send A Message From Your Freename Domain Name从您的 Freename 域名撰写和发送消息
Log into your Mailchain account.登录您的 Mailchain 帐户。
Click 'Compose' in the sidebar.单击边栏中的“撰写”。
In the New Message window, click the “From” dropdown menu.在“新消息”窗口中,单击“发件人”下拉菜单。
Select your Freename name.选择您的自由名称。
Fill out the rest of the message, then click Send.
Below, the recipients are:
allofweb3.hodl and sendto.moon@freename. To learn more about naming conventions, see shorthand addressing with Freename.
填写消息的其余部分,然后单击“发送”。下面,收件人是:allofweb3.hodl 和 sendto.moon@freename。要了解有关命名约定的更多信息,请参阅使用自由名称的速记寻址。
Your message should be successfully sent.您的消息应该已成功发送。
Done! Your recipient will receive your message from your Freename domain.完毕!您的收件人将从您的 Freename 域收到您的消息。
Frequently asked questions for working with Freename and Mailchain.使用 Freename 和 Mailchain 的常见问题解答。
How do I register an Freename domain name?如何注册 Freename 域名?
Visit Freename.io and follow instructions on their site.访问 Freename.io 并按照其网站上的说明进行操作。
Can someone send me a Mailchain message to my Freename top-level domain (TLD) or second-level domain (SLD)?有人可以向我的 Freename 顶级域 (TLD) 或二级域 (SLD) 发送 Mailchain 消息吗?
You can ask anyone to send messages to your Freename TLD or SLD using the address format below: Does Mailchain support shorthand addressing for Freename您可以要求任何人使用以下地址格式向您的 Freename TLD 或 SLD 发送消息:Does Mailchain support shorthand addressing for Freename
What happens when someone sends a message to my Freename domain in Mailchain?当有人向我在 Mailchain 中的 Freename 域发送消息时会发生什么?
When someone sends a Mailchain message to a Freename domain, Mailchain resolves the Freename domain and delivers the message to the resolved address (the address of registered owner of the Freename NFT).当有人向 Freename 域发送 Mailchain 消息时,Mailchain 解析 Freename 域并将消息传递到解析地址(Freename NFT 的注册所有者的地址)。
If you are the owner of the minted name, then the message will arrive in your inbox.如果您是铸造名称的所有者,则该消息将到达您的收件箱。
What if I have not yet registered my wallet address with Mailchain?如果我还没有在 Mailchain 注册我的钱包地址怎么办?
If you have not yet registered the wallet address with Mailchain, the protocol will still accept the encrypted message and store it for up to 90 days. You can synchronize messages for this address when you register the wallet address. (See How to add your Freename domain to Mailchain)如果您尚未在 Mailchain 注册钱包地址,该协议仍会接受加密消息并将其存储最多 90 天。您可以在注册钱包地址时同步该地址的消息。 (请参阅如何将您的 Freename 域添加到 Mailchain)
My Freename domain was not found, what should I check?找不到我的 Freename 域,我应该检查什么?
Check you are registering the intended wallet address检查您是否正在注册预期的钱包地址
Check your Freename domain is minted and in your wallet检查您的 Freename 域是否已创建并在您的钱包中
How does Mailchain resolve Freename domains?Mailchain 如何解析 Freename 域?
Mailchain will always resolve the name from the Freename.io resolver API so it will reflect the latest changes returned by the resolver.Mailchain 将始终从 Freename.io 解析器 API 解析名称,因此它将反映解析器返回的最新更改。
What address record does Mailchain use when it resolves a name?Mailchain 在解析名称时使用什么地址记录?
Mailchain will resolve and return the first valid record from this order: ETH record, Owner record.Mailchain 将解析并返回此订单的第一个有效记录:ETH 记录、Owner 记录。
What happens if I no longer own my Freename domain?如果我不再拥有我的 Freename 域名会怎样?
If the Freename domain no longer resolves to your address, Mailchain messages will no longer be sent to your address either. If someone else registers a wallet address in Mailchain that the Freename domain resolves to, they will receive messages sent to the Freename domain. This will not have any impact on messages already in your inbox.如果 Freename 域不再解析为您的地址,则 Mailchain 消息也将不再发送到您的地址。如果其他人在 Freename 域解析到的 Mailchain 中注册了一个钱包地址,他们将收到发送到 Freename 域的消息。这不会对您收件箱中已有的邮件产生任何影响。
Does Mailchain support shorthand addressing for Freename?Mailchain 是否支持 Freename 的速记寻址?
Mailchain users can use their Unstoppable Domains to send and receive messages. It’s simple to get started…Mailchain 用户可以使用他们的 Unstoppable Domains 来发送和接收消息。上手很简单……
Introduction介绍
Unstoppable Domains is an NFT domain name provider and digital identity platform working to onboard the world onto Web3. Unstoppable Domains offers NFT domains minted on the blockchain that give people full ownership and control of their digital identity, with no renewal fees. With Unstoppable Domains, people can replace lengthy alphanumeric crypto wallet addresses with a human-readable name and log into and transact with apps, wallets, exchanges and marketplaces.Unstoppable Domains 是一个 NFT 域名提供商和数字身份平台,致力于将世界载入 Web3。 Unstoppable Domains 提供在区块链上铸造的 NFT 域,让人们完全拥有和控制他们的数字身份,无需续订费用。借助 Unstoppable Domains,人们可以将冗长的字母数字加密钱包地址替换为人类可读的名称,并登录应用程序、钱包、交易所和市场并进行交易。
How To Add Your Unstoppable Domain (UD) Name To Mailchain如何将不可阻挡的域名 (UD) 添加到邮件链
You need to have a valid, minted Unstoppable Domain owned by your address (see Unstoppable Domains docs for more information on how to do this)您需要拥有一个由您的地址拥有的有效的、铸造的 Unstoppable 域(有关如何执行此操作的更多信息,请参阅 Unstoppable Domains 文档)
You have a Mailchain account (see here)您有一个 Mailchain 帐户(请参阅此处)
Log in to your Mailchain Account.登录到您的 Mailchain 帐户。
Click “Register Your Wallet”.点击“注册你的钱包”。
A modal will open. Select a wallet provider (e.g. Metamask), then click 'Connect'将打开一个模态。选择钱包提供商(例如 Metamask),然后单击“连接”
Choose the address to connect, then click Next.选择要连接的地址,然后单击下一步。
Click 'Connect' to confirm Mailchain should be able to read your address.单击“连接”以确认 Mailchain 应该能够读取您的地址。
The address is now connected, but we need to register it in Mailchain. To do this, click 'Verify Address'该地址现已连接,但我们需要在 Mailchain 中注册它。为此,请单击“验证地址”
A 'Signature Request' will appear in your wallet. It contains the following text:“签名请求”将出现在您的钱包中。它包含以下文本:
Message: Welcome to Mailchain! Please sign to start using this address with Mailchain. This will not trigger a blockchain transaction or cost any gas fees. What's happening? A messaging key will be registered with this address and used only for messaging. It will replace any existing registered messaging keys. Technical Details: Address: `your_address` Messaging key: `a_generated_messaging_key` Nonce: `a_number`
Review the request and click 'Sign' to complete verification.查看请求并单击“签名”以完成验证。
The next step checks for connected name services, including UD names. This example found epistola.crypto & mailchain.888. If you do not see your UD name here, you can manually search for it using the search box. If it still cannot be found, please see Unstoppable Domains FAQs here.
下一步检查连接的名称服务,包括 UD 名称。这个例子找到了 epistola.crypto & mailchain.888。如果您在这里没有看到您的 UD 名称,您可以使用搜索框手动搜索它。如果仍然找不到,请在此处查看 Unstoppable Domains 常见问题解答。
You can add a custom label for your address. By default, Mailchain will populate your UD name. Click Apply to save and continue.您可以为地址添加自定义标签。默认情况下,Mailchain 将填充您的 UD 名称。单击“应用”以保存并继续。
Mailchain is able to receive messages for your wallet address before you sign up. Click 'Synchronize' to retrieve these messages, or click 'Skip' to synchronize later. Any synchronized messages will appear in your inbox.Mailchain 能够在您注册之前接收您的钱包地址的消息。单击“同步”以检索这些消息,或单击“跳过”以稍后同步。任何同步的消息都会出现在您的收件箱中。
You can now click 'Done' to disconnect your wallet and close the modal, or choose to register another address.您现在可以单击“完成”以断开您的钱包并关闭模式,或选择注册另一个地址。
You will now see the newly added inbox on the left. This will be labelled with the label you provided when registering the address. Any messages sent to that address or the UD name will appear in this inbox.您现在将在左侧看到新添加的收件箱。这将标有您在注册地址时提供的标签。发送到该地址或 UD 名称的任何消息都将显示在此收件箱中。
How To Send A Message Using Your UD Name如何使用您的 UD 名称发送消息
With Mailchain you can send Mailchain message from your Unstoppable Domain name to other Mailchain users.使用 Mailchain,您可以从您不可阻挡的域名向其他 Mailchain 用户发送 Mailchain 消息。
You need to have a valid, minted Unstoppable Domain owned by your address (see Unstoppable Domains docs for more information on how to do this)您需要拥有一个由您的地址拥有的有效的、铸造的 Unstoppable 域(有关如何执行此操作的更多信息,请参阅 Unstoppable Domains 文档)
You have a Mailchain account (see here)您有一个 Mailchain 帐户(请参阅此处)
You have added your Unstoppable Domain name to Mailchain (see above)您已将 Unstoppable 域名添加到 Mailchain(见上文)
Compose And Send A Message From Your UD Name使用您的 UD 名称撰写和发送消息
Log into your Mailchain account.登录您的 Mailchain 帐户。
Click 'Compose' in the sidebar.单击边栏中的“撰写”。
In the New Message window, click arrows to expand the compose message modal.在“新消息”窗口中,单击箭头以展开撰写消息模式。
In the New Message window, click the “From” dropdown menu and select your UD name.在“新消息”窗口中,单击“发件人”下拉菜单并选择您的 UD 名称。
In the To field, add your recipient. The autocomplete will offer suggestions for common Web3 names.在“收件人”字段中,添加您的收件人。自动完成功能将为常见的 Web3 名称提供建议。
Fill out the rest of the message, then click Send填写消息的其余部分,然后单击“发送”
Your message should be successfully sent.您的消息应该已成功发送。
Done! Your recipient will receive your message from your Unstoppable Domain name.完毕!您的收件人将从您不可阻挡的域名收到您的消息。
Frequently asked questions for working with Unstoppable Domains (UD) and Mailchain.使用 Unstoppable Domains (UD) 和 Mailchain 的常见问题解答。
Can someone send me a Mailchain message to my UD name?有人可以向我的 UD 名称发送邮件链消息吗?
You can ask anyone to send messages to your UD name… it’s a Web3 identity afterall!您可以要求任何人向您的 UD 名称发送消息……毕竟这是 Web3 身份!
What happens when someone sends a message to my UD name in Mailchain?当有人向我在 Mailchain 中的 UD 名称发送消息时会发生什么?
When someone sends a Mailchain message to a UD name, Mailchain resolves the UD name and delivers the message to the resolved owner address.当有人向 UD 名称发送 Mailchain 消息时,Mailchain 解析 UD 名称并将消息传递到解析的所有者地址。
If you have already registered the wallet address, then the message will arrive in your inbox.如果您已经注册了钱包地址,那么该消息将到达您的收件箱。
What if I have not yet registered my wallet address with Mailchain?如果我还没有在 Mailchain 注册我的钱包地址怎么办?
If you have not yet registered the wallet address with Mailchain, the protocol will still accept the encrypted message and store it for up to 90 days. You can synchronise messages for this address when you register the wallet address. (See How to add your Unstoppable Domain to Mailchain)如果您尚未在 Mailchain 注册钱包地址,该协议仍会接受加密消息并将其存储最多 90 天。您可以在注册钱包地址时同步该地址的消息。 (请参阅如何将 Unstoppable 域添加到 Mailchain)
What happens if I no longer own my UD name?如果我不再拥有我的 UD 名字会怎样?
If your address is no longer the owner of the UD name, it will not resolve and Mailchain messages will no longer be sent to the address. If someone else registers the address that owns the name in Mailchain, they will be able to receive messages sent to the UD name. This will not have any impact on messages already in your inbox.如果您的地址不再是 UD 名称的所有者,它将无法解析并且 Mailchain 消息将不再发送到该地址。如果其他人在 Mailchain 中注册了拥有该名称的地址,他们将能够接收发送到该 UD 名称的消息。这不会对您收件箱中已有的邮件产生任何影响。
My UD name was not found, what should I check?找不到我的 UD 名称,我应该检查什么?
Check you are registering the intended wallet address.检查您是否正在注册预期的钱包地址。
Check that the address appears in the https://ud.me profile.检查该地址是否出现在 https://ud.me 配置文件中。
How does Mailchain resolve UD names?Mailchain 如何解析 UD 名称?
Mailchain uses the Unstoppable Domains resolver API, so results will always reflect the Unstoppable Domains registry.Mailchain 使用 Unstoppable Domains 解析器 API,因此结果将始终反映 Unstoppable Domains 注册表。
Do I need to mint an Unstoppable Domain to use it with Mailchain?我是否需要创建一个不可阻挡的域才能将其与 Mailchain 一起使用?
Yes, you need to "mint" your Unstoppable Domain to be able to use it with Mailchain. The process of minting generates the NFT domain and sends it to the owner's address.是的,您需要“铸造”您的 Unstoppable Domain 才能将其与 Mailchain 一起使用。铸币过程生成 NFT 域并将其发送到所有者的地址。
Which Unstoppable Domains top level domains do you support?您支持哪些 Unstoppable Domains 顶级域名?
Mailchain supports sending and receiving messages for any Unstoppable Domain top-level domain (TLD).Mailchain 支持发送和接收任何 Unstoppable Domain 顶级域 (TLD) 的消息。
Does Mailchain support shorthand addressing for Unstoppable Domains?Mailchain 是否支持 Unstoppable Domains 的速记寻址?
Your Secret Recovery Phrase, otherwise known as a mnemonic "Secret Recovery Phrase" is used to mathematically derive all the messaging keys, private keys, signatures and other secrets for your account.您的秘密恢复短语,也称为助记“秘密恢复短语”,用于从数学上推导您帐户的所有消息密钥、私钥、签名和其他秘密。
It should never be shared with anyone because doing so would give full, irrevocable access to your account. A Secret Recovery Phrase cannot be changed or recovered.永远不要与任何人共享它,因为这样做会提供对您帐户的完全、不可撤销的访问权限。秘密恢复短语无法更改或恢复。
Log in to your Mailchain Account.登录到您的 Mailchain 帐户。
Click ‘Settings’.点击“设置”。
Go to the ‘Secret recovery phrase‘ section and click ‘Download’.转到“秘密恢复短语”部分,然后单击“下载”。
Fill in your password and prove you are not a robot.填写您的密码并证明您不是机器人。
Click ‘Confirm’点击“确认”
Your Secret Recovery Phrase will be downloaded to your device as a text file (.txt).您的秘密恢复短语将作为文本文件 (.txt) 下载到您的设备。
When you open the file, you will see your secret recovery phrase.当您打开文件时,您会看到您的秘密助记词。
danger危险
Store your Secret Recovery Phrase securely. It should never be shared with anyone because doing so would give full, irrevocable access to your account.安全地存储您的秘密恢复短语。永远不要与任何人共享它,因为这样做会提供对您帐户的完全、不可撤销的访问权限。
Keeping your users informed is important, but hard to do in Web3.让你的用户了解情况很重要,但在 Web3 中很难做到。
Mailchain is a multi-chain communication protocol that helps you communicate with your users across any protocol. It provides end-to-end encryption by default, and supports 1:1, 1:many and group messaging.Mailchain 是一种多链通信协议,可帮助您跨任何协议与用户进行通信。默认提供端到端加密,支持1:1、1:many和群发。
Using Mailchain you can easily send messages to any blockchain address on different protocols. Mailchain solves your messaging needs so you can focus on building your application.使用 Mailchain,您可以轻松地将消息发送到不同协议上的任何区块链地址。 Mailchain 解决了您的消息传递需求,因此您可以专注于构建您的应用程序。
The preferred way to integrate with Mailchain is using our SDK. It takes care of the complexity working with the REST API including signing, verifying, encrypting, and decrypting.与 Mailchain 集成的首选方式是使用我们的 SDK。它负责处理使用 REST API 的复杂性,包括签名、验证、加密和解密。
The API is on course to be decentralized and could be run by anyone. This presents some additional considerations when you call the endpoints. We built the SDK with these in mind and it securely handles the following specifications:API 正在去中心化,任何人都可以运行。当您调用端点时,这会提出一些额外的注意事项。我们在构建 SDK 时考虑到了这些,它可以安全地处理以下规范:
Requests MUST be authenticated before they are transmitted, using the correct key.请求必须在传输之前使用正确的密钥进行身份验证。
Requests containing private data MUST be encrypted with the correct key before being transmitted.包含私有数据的请求必须在传输前用正确的密钥加密。
Responses MUST be verified to ensure they are valid and up to date.必须验证响应以确保它们有效且是最新的。
Responses containing encrypted data MUST be decrypted with the correct key before being read by the application.包含加密数据的响应必须在被应用程序读取之前用正确的密钥解密。
The SDK handles this safely and has a simple interface so you can easily send messages and work with validated API responses. The SDK is open source and the API is open to the public so you can independently verify this at any time.SDK 可以安全地处理此问题并具有简单的界面,因此您可以轻松发送消息并使用经过验证的 API 响应。 SDK 是开源的,API 是对外开放的,您可以随时独立验证。
We think using the SDK is a better choice than calling the API directly, and we’d love to hear your feedback on how we can make it even better.我们认为使用 SDK 是比直接调用 API 更好的选择,我们很乐意听取您的反馈,告诉我们如何才能让它变得更好。
Adding Mailchain to your application is easy. Mailchain's SDK makes interacting with the Mailchain protocol simple. Using the SDK you will be able to send, receive (coming soon... for now you can view replies in https://app.mailchain.com) and register addresses (coming soon).将 Mailchain 添加到您的应用程序很容易。 Mailchain 的 SDK 使与 Mailchain 协议的交互变得简单。使用 SDK,您将能够发送、接收(即将推出……目前您可以在 https://app.mailchain.com 中查看回复)和注册地址(即将推出)。
To add Mailchain's SDK to your application install via your package manager of choice.通过您选择的包管理器将 Mailchain 的 SDK 添加到您的应用程序安装中。
Mailchain addressing provides broad support for known address schemes, including Mailchain accounts and identities, blockchain protocol addresses, Web3 names, and traditional email. The format is based on the RFC5322 Addr-Spec Specification to ensure maximum compatibility with other programs and future-proof support for potential address schemes (‘local-part’@’domain-part’).Mailchain 寻址为已知地址方案提供广泛支持,包括 Mailchain 帐户和身份、区块链协议地址、Web3 名称和传统电子邮件。该格式基于 RFC5322 Addr-Spec 规范,以确保与其他程序的最大兼容性和对潜在地址方案(‘local-part’@’domain-part’)的未来证明支持。
Please refer to the table below for definition and examples:定义和示例请参考下表:
Each name service may support a shorthand address format (e.g. alice.eth for ENS). Please see name service FAQs for specific name service shorthands:每个名称服务都可能支持速记地址格式(例如,ENS 的 alice.eth)。请参阅名称服务常见问题解答以了解特定的名称服务缩写:
You own and control your account and its data. Mailchain does not have access to any data or messages. Access is only possible using your username and password combination or Secret Recovery Phrase. Mailchain cannot reset your credentials.您拥有并控制您的帐户及其数据。 Mailchain 无权访问任何数据或消息。只能使用您的用户名和密码组合或秘密恢复短语进行访问。 Mailchain 无法重置您的凭据。
note笔记
You need a Mailchain account before you can authenticate with the SDK. You can create an account through the app.在使用 SDK 进行身份验证之前,您需要一个 Mailchain 帐户。您可以通过该应用程序创建一个帐户。
Mailchain SDK's uses your private key to sign, decrypt and hash data. You need to authenticate the SDK to use any of the private methods such as sending a message.Mailchain SDK 使用您的私钥来签署、解密和散列数据。您需要对 SDK 进行身份验证才能使用任何私有方法,例如发送消息。
Your private key never leaves your machine.您的私钥永远不会离开您的机器。
There are multiple way to provide your private key to the Mailchain SDK. You can authenticate with your Secret Recovery Phrase, seed bytes, or password (coming soon).有多种方法可以将您的私钥提供给 Mailchain SDK。您可以使用您的秘密恢复短语、种子字节或密码(即将推出)进行身份验证。
danger危险
Your Secret Recovery Phrase, seed bytes, or private key can not be changed. They should be stored encrypted and provided to your application securely.您的秘密恢复短语、种子字节或私钥无法更改。它们应该加密存储并安全地提供给您的应用程序。
Use your Secret Recovery Phrase to provide your private key to the SDK. Secret Recovery Phrase's, a 24 word BIP 39 compatible mnemonic phrase, which is used to create your private key.使用您的秘密恢复短语向 SDK 提供您的私钥。 Secret Recovery Phrase's,一个 24 字的 BIP 39 兼容助记词,用于创建您的私钥。
You can verify that the Secret Recovery Phrase you provided by verifying the authenticated user details.您可以通过验证经过身份验证的用户详细信息来验证您提供的秘密恢复短语。
info信息
Your Secret Recovery Phrase is available when you created your Mailchain account. You can can also to view or download your Secret Recovery Phrase from the settings page within the Mailchain application.当您创建 Mailchain 帐户时,您的秘密恢复短语可用。您还可以从 Mailchain 应用程序的设置页面查看或下载您的 Secret Recovery Phrase。
A good way to verify that the account exists and get information about the registered user is to call the .user() method.验证帐户是否存在并获取有关注册用户的信息的一个好方法是调用 .user() 方法。
const user =await mailchain.user(); console.log(`username: ${user.username}, address: ${user.address}`);
This will display your account username and Mailchain account address.
The Mailchain SDK is now authenticated and you can start sending messages.这将显示您的帐户用户名和 Mailchain 帐户地址。 Mailchain SDK 现已通过身份验证,您可以开始发送消息。
Using Mailchain you can send a message to any blockchain address. Only the owner of the address will be able to receive and read the message.使用 Mailchain,您可以将消息发送到任何区块链地址。只有地址的所有者才能接收和阅读消息。
import{ Mailchain }from'@mailchain/sdk'; const secretRecoveryPhrase = process.env.SECRET_RECOVERY_PHRASE!;// 25 word mnemonicPhrase const mailchain = Mailchain.fromSecretRecoveryPhrase(secretRecoveryPhrase); const result =await mailchain.sendMail({ from:`yoursername@mailchain.com`,// sender address to:[`0xbb56FbD7A2caC3e4C17936027102344127b7a112@ethereum.mailchain.com`],// list of recipients (blockchain or mailchain addresses) subject:'My first message',// subject line content:{ text:'Hello Mailchain 👋',// plain text body html:'<p>Hello Mailchain 👋</p>',// html body }, }); console.log(result);
note笔记
You can send a message to your username@mailchain, or if you've registered an ethereum address you can send a message to it (e.g. 0x.....@ethereum.mailchain.com). You can also try sending a message to 0xbb56FbD7A2caC3e4C17936027102344127b7a112@ethereum.mailchain.com, that's a valid, unmonitored address at Mailchain, we own the private key for it.您可以向您的用户名@mailchain 发送消息,或者如果您已经注册了一个以太坊地址,您可以向它发送消息(例如 0x.....@ethereum.mailchain.com)。您也可以尝试向 0xbb56FbD7A2caC3e4C17936027102344127b7a112@ethereum.mailchain.com 发送消息,这是一个有效的、不受监控的 Mailchain 地址,我们拥有它的私钥。
After the message is successfully sent you will be able to see it in your sent folder and the recipient will see it in their inbox.邮件发送成功后,您将能够在您的已发送文件夹中看到它,收件人将在他们的收件箱中看到它。
note笔记
The Mailchain app checks for messages and updates the inbox in the background. You can force a refresh by clicking on the refresh icon above the list of messages.Mailchain 应用程序检查消息并在后台更新收件箱。您可以通过单击消息列表上方的刷新图标来强制刷新。
At the end of this tutorial, you will have built an Express App, that exposes an API you can use to send messages with Mailchain. Your app will use the Mailchain SDK that handles signatures, encryption, and sending the message. In most cases, you would add a route to an existing Express App, but for this tutorial, you'll create a new app.在本教程结束时,您将构建一个 Express 应用程序,它公开了一个 API,您可以使用该 API 通过 Mailchain 发送消息。您的应用程序将使用处理签名、加密和发送消息的 Mailchain SDK。在大多数情况下,您会向现有的 Express 应用添加路由,但对于本教程,您将创建一个新应用。
You can find the final code and working example in mailchain/examples-js on GitHub.您可以在 GitHub 上的 mailchain/examples-js 中找到最终代码和工作示例。
You'll create a new Express app that exposes an API, the simplest way to do that is with a generator that creates an Express App structure. There are various express generators, for this tutorial you'll use typescript-express-starter.您将创建一个公开 API 的新 Express 应用程序,最简单的方法是使用创建 Express App 结构的生成器。有多种快速生成器,对于本教程,您将使用 typescript-express-starter。
To begin, open a terminal window on your computer and run:首先,在您的计算机上打开一个终端窗口并运行:
typescript-express-starter does change from time to time, so using typescript-express-starter@9.2.0 guarantees this tutorial completes successfully.typescript-express-starter 确实会不时更改,因此使用 typescript-express-starter@9.2.0 可以保证本教程成功完成。
If you get a message similar to below, likely it because it's the first time using npx to run express generator, or this specific version. Press y to continue, you'll only need to do this once.如果您收到类似下面的消息,可能是因为它是第一次使用 npx 运行 express generator,或者是这个特定版本。按 y 继续,您只需执行一次。
Need to install the following packages: typescript-express-starter@9.2.0 Ok to proceed? (y)
typescript-express-starter will ask you for some details:typescript-express-starter 会要求您提供一些详细信息:
Accept the default template, by pressing enter.按 enter 键接受默认模板。
Press n when asked to update to the latest packages, this guarantees this tutorial completes successfully.当要求更新到最新包时按 n,这保证本教程成功完成。
Press y when asked to removed duplicate packages at npm.当要求删除 npm 上的重复包时按 y。
typescript-express-starter can take a while to create a new project as it's installing npm packages. Once completed typescript-express-starter will confirm it's status:typescript-express-starter 可能需要一段时间才能创建一个新项目,因为它正在安装 npm 包。完成后,typescript-express-starter 将确认其状态:
? Please select the template you want default ? Do you want to update all packages in the node_modules directory and dependency ? No ? Do you want to Used to removed duplicate packages at npm ? Yes [ 1 / 3 ] 🔍 copying project... [ 2 / 3 ] 🚚 fetching node_modules... [ 3 / 3 ] 🔗 linking node_modules... ───────────────────────────────────────── ✔ Complete setup project
Your Express App is now created. Open mailchain-send-api in your favorite code editor. You'll see it contains example services, controllers, routes, etc. Later you'll extend this functionality.您的 Express 应用现已创建。在您喜欢的代码编辑器中打开 mailchain-send-api。您会看到它包含示例服务、控制器、路由等。稍后您将扩展此功能。
Check you can start your mailchain-send-api app in development mode by running:检查您是否可以通过运行以下命令以开发模式启动您的 mailchain-send-api 应用程序:
cd mailchain-send-api &&npm run dev
The output should look like:输出应如下所示:
[nodemon] 2.0.20 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): src/**/* .env [nodemon] watching extensions: js,ts,json [nodemon] starting `ts-node -r tsconfig-paths/register --transpile-only src/server.ts` info: ================================= info: ======= ENV: development ======= info: 🚀 App listening on the port 3000 info: =================================
This confirms that the app started correctly and can be accessed via http://localhost:3000.这确认应用程序正确启动并且可以通过 http://localhost:3000 访问。
Press ctrl + c together, this will stop the Express App.同时按 ctrl + c,这将停止 Express 应用程序。
Mailchain SDK is the easiest way to use Mailchain, it deals with all of the encryption, signatures, and hashing for you.Mailchain SDK 是使用 Mailchain 的最简单方法,它为您处理所有加密、签名和散列。
To install the Mailchain SDK you need to run an npm command in the base directory of your project mailchain-send-api. If you are following Step 1, you should already be in this folder. Otherwise, open up a terminal window and navigate to your mailchain-send-api folder.要安装 Mailchain SDK,您需要在项目 mailchain-send-api 的基本目录中运行 npm 命令。如果您正在执行第 1 步,则您应该已经位于该文件夹中。否则,打开一个终端窗口并导航到您的 mailchain-send-api 文件夹。
Install Mailchain SDK using npm:使用 npm 安装 Mailchain SDK:
npminstall --save @mailchain/sdk
note笔记
npm installed Mailchain SDK and added it as dependency to your project. You can see this change by opening package.json, you'll find an entry for @mailchain/sdk. This tells package the package manager that @mailchain/sdk is a dependency and should be installed with other dependencies.npm 安装了 Mailchain SDK 并将其作为依赖项添加到您的项目中。您可以通过打开 package.json 来查看此更改,您将找到 @mailchain/sdk 的条目。这告诉包管理器 @mailchain/sdk 是一个依赖项,应该与其他依赖项一起安装。
A Mailchain account is web3 identity, this means that the account is created via a private key that the user owns and controls. In Mailchain's case, the Secret Recovery Phrase creates the private key.Mailchain 帐户是 web3 身份,这意味着该帐户是通过用户拥有和控制的私钥创建的。在 Mailchain 的例子中,Secret Recovery Phrase 创建私钥。
danger危险
Whoever has the Secret Recovery Phrase controls the account. You should treat Secret Recovery Phrases as if they are private keys. They MUST be kept safely and only saved in a trusted store.谁拥有秘密恢复短语,谁就控制该帐户。您应该将 Secret Recovery Phrases 视为私钥。它们必须安全保存,并且只能保存在受信任的商店中。
We suggest for development and testing that you use a Secret Recovery Phrase from a test account. Go ahead and create a new account if you don't already have one. Your Secret Recovery Phrase is available to view or download when you register your account. To get your Secret Recovery Phrase afterward go to the settings page and look for the Secret Recovery Phrase section.我们建议您使用测试帐户中的秘密恢复短语进行开发和测试。如果您还没有,请继续创建一个新帐户。当您注册您的帐户时,您的秘密恢复短语可供查看或下载。之后要获取您的秘密恢复短语,请转到设置页面并查找秘密恢复短语部分。
The Mailchain SDK needs to be authenticated with your Secret Recovery Phrase to send messages. We are assuming you are developing on a local machine and it is secure.Mailchain SDK 需要使用您的 Secret Recovery Phrase 进行身份验证才能发送消息。我们假设您正在本地机器上开发并且它是安全的。
Environment variables let you set values that are passed to your server-side code. Your code sets environment variables using env files. The environment files are in the root directory of your app and are named according to the environment, e.g. .env.development.local.环境变量允许您设置传递给服务器端代码的值。您的代码使用 env 文件设置环境变量。环境文件位于应用程序的根目录中,并根据环境命名,例如.env.development.local。
danger危险
Care must be taken to avoid storing environment variables in source control. For this tutorial, there is a .gitignore file. This tells git to ignore each of the existing environment files. This prevents changes to the existing environment files from being stored in git. Make sure you add new environments to .gitignore.必须注意避免在源代码管理中存储环境变量。对于本教程,有一个 .gitignore 文件。这告诉 git 忽略每个现有的环境文件。这可以防止对现有环境文件的更改存储在 git 中。确保将新环境添加到 .gitignore。
Use your test development account's Secret Recovery Phrase that you retrieved from the previous step. Open .env.development.local in your editor, and add a new line to the bottom SECRET_RECOVERY_PHRASE=enter your secret phrase here.使用您从上一步中检索到的测试开发帐户的秘密恢复短语。在您的编辑器中打开 .env.development.local,并在底部添加一个新行 SECRET_RECOVERY_PHRASE=在此处输入您的密码。
Replace enter your secret phrase here with your Secret Recovery Phrase and save the file.用您的 Secret Recovery Phrase 替换 enter your secret phrase 并保存文件。
After your .env.development.local should look similar to this:在你的 .env.development.local 应该看起来类似于这样:
# PORT PORT = 3000 SECRET_RECOVERY_PHRASE=enter your secret phrase here
In your terminal window run, npm run dev from the root directory of your mailchain-send-api app. You should get a response similar to below:在终端窗口运行中,从 mailchain-send-api 应用程序的根目录运行 npm dev。您应该会得到类似于以下的响应:
info: ================================= info: ======= ENV: development ======= info: 🚀 App listening on the port 3000 info: =================================
This means is successfully started and listening on port 3000.这意味着已成功启动并侦听端口 3000。
note笔记
nodemon automatically restarts your API when file changes are detected. However, it doesn't pick up changes to .env.development.local so you need to restart the server manually by pressing ctrl + c and running npm run dev. You'll only need to restart the app when changing the SECRET_RECOVERY_PHRASE setting.当检测到文件更改时,nodemon 会自动重启您的 API。但是,它不会获取对 .env.development.local 的更改,因此您需要通过按 ctrl + c 并运行 npm run dev 来手动重启服务器。您只需在更改 SECRET_RECOVERY_PHRASE 设置时重新启动应用程序。
Step 3 - Create a service for sending mail第 3 步 - 创建用于发送邮件的服务
Express uses services to perform tasks, in this case sending mail using the Mailchain SDK. The service will send messages using the account based on the SECRET_RECOVERY_PHRASE environment variable.Express 使用服务来执行任务,在本例中使用 Mailchain SDK 发送邮件。该服务将使用基于 SECRET_RECOVERY_PHRASE 环境变量的帐户发送消息。
MailService will perform the following actions:MailService 将执行以下操作:
Authenticate the Mailchain SDK using the SECRET_RECOVERY_PHRASE.使用 SECRET_RECOVERY_PHRASE 验证 Mailchain SDK。
Set the from address to the currently authenticated user if it's not supplied.如果未提供,请将发件人地址设置为当前经过身份验证的用户。
Send mail using the Mailchain SDK.使用 Mailchain SDK 发送邮件。
Inside src/services/ create mail.service.ts and copy the code below into it.在 src/services/ 中创建 mail.service.ts 并将下面的代码复制到其中。
import{ Mailchain, SendMailParams, SendMailResult }from'@mailchain/sdk'; classMailService{ asyncsend(params: SendMailParams):Promise<SendMailResult>{ // use the environment variable to provide your secret recovery phrase const secretRecoveryPhrase = process.env.SECRET_RECOVERY_PHRASE; if(secretRecoveryPhrase ==null){ thrownewError('You must provide a secret recovery phrase'); } const mailchain = Mailchain.fromSecretRecoveryPhrase(secretRecoveryPhrase); if(!params.from || params.from ===''){ // set the from address to current user if not provided const currentUser =await mailchain.user(); params.from = currentUser.address; } returnawait mailchain.sendMail(params); } } exportdefault MailService;
Remember to save mail.service.ts after pasting the code.粘贴代码后记得保存mail.service.ts。
Controllers manage the incoming HTTP requests and send the necessary data to the correct service.控制器管理传入的 HTTP 请求并将必要的数据发送到正确的服务。
MailController will perform the following actions:MailController 将执行以下操作:
Pass the HTTP request body to the send service.将 HTTP 请求正文传递给发送服务。
Set the HTTP response status field using the SDK response.使用 SDK 响应设置 HTTP 响应状态字段。
In your editor create mail.controller.ts in the src/controllers/ folder. Copy and paste the code below into it.在您的编辑器中,在 src/controllers/ 文件夹中创建 mail.controller.ts。将下面的代码复制并粘贴到其中。
RESTful API's are designed around paths and methods, in Express these are created in the src/routes folder.RESTful API 是围绕路径和方法设计的,在 Express 中,这些是在 src/routes 文件夹中创建的。
The API is called by clients using HTTP. The HTTP interface is modeled as a RESTful API making it familiar for developers and easy to discover. You'll create an additional route that accepts mail parameters. The route will use the sendMail function you created in Step 3 above.API 由使用 HTTP 的客户端调用。 HTTP 接口被建模为 RESTful API,使开发人员熟悉并且易于发现。您将创建一个接受邮件参数的附加路由。该路由将使用您在上面的第 3 步中创建的 sendMail 函数。
MailRoute performs the following actions:MailRoute 执行以下操作:
Adds the send path.添加发送路径。
Listens for a POST.侦听 POST。
Route request to the mail controller.将请求路由到邮件控制器。
In your editor create mail.route.ts in the src/routes/ folder. Copy and paste the code below into it.在您的编辑器中,在 src/routes/ 文件夹中创建 mail.route.ts。将下面的代码复制并粘贴到其中。
Now MailRoute has been created, the final code change is to add MailRoute to the server.现在已经创建了 MailRoute,最后的代码更改是将 MailRoute 添加到服务器。
The server code:服务器代码:
Adds routes.添加路由。
Listens to incoming requests.侦听传入请求。
In your editor open the existing server.ts file in the src/ folder. Replace the existing contents by copying and pasting the code below into it.在您的编辑器中打开 src/ 文件夹中的现有 server.ts 文件。通过将下面的代码复制并粘贴到其中来替换现有内容。
Now you have API that can send messages. You can test this by sending a sample request via HTTP.现在您有了可以发送消息的 API。您可以通过 HTTP 发送示例请求来对此进行测试。
note笔记
Your Express App needs to be running to accept requests. If your Express App is not already running, open your terminal and navigate to the base directory of your project e.g. mailchain-send-api then run npm run dev to start your Express app.您的 Express App 需要运行才能接受请求。如果您的 Express App 尚未运行,请打开您的终端并导航至项目的基本目录,例如mailchain-send-api 然后运行 npm run dev 来启动你的 Express 应用程序。
You can now test your API by sending a message. Open a new terminal window, and paste the following curl command into a terminal window.您现在可以通过发送消息来测试您的 API。打开一个新的终端窗口,并将以下 curl 命令粘贴到终端窗口中。
After a few seconds, you should get a response that looks a bit like this:几秒钟后,您应该会收到如下所示的响应:
HTTP/1.1 200 OK Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true ... {"status":"success"}
200 OK means that it worked. 200 is the HTTP response code for success. You can check the message has been sent by looking in the sent folder in the Mailchain web app. Awesome you have sent a Mailchain message via your API.200 OK 表示它有效。 200 是成功的 HTTP 响应代码。您可以通过查看 Mailchain Web 应用程序中的已发送文件夹来检查邮件是否已发送。太棒了,您已经通过 API 发送了邮件链消息。
Want to try more? Edit the curl command above and try to:想尝试更多吗?编辑上面的 curl 命令并尝试:
Send a message to your Mailchain account. Change the to address "<username>@mailchain.com". Check your inbox and you'll see your message. ✅向您的 Mailchain 帐户发送消息。更改地址“<用户名>@mailchain.com”。检查您的收件箱,您会看到您的消息。 ✅
Do you want to send mail to an Ethereum address? Register your Ethereum address in the Mailchain application. Then send a message to <ethereum-address>@ethereum.mailchain.com. ✅您想将邮件发送到以太坊地址吗?在 Mailchain 应用程序中注册您的以太坊地址。然后发送消息到 <ethereum-address>@ethereum.mailchain.com。 ✅
note笔记
I get status 200 OK but I can't see the message in the sent folder. 200 means the API responded correctly, the message should have been sent. Make sure you are logged in with your development/testing account and try refreshing the sent folder.我的状态为 200 OK,但我在已发送文件夹中看不到消息。 200 表示 API 响应正确,消息应该已发送。确保您已使用开发/测试帐户登录并尝试刷新已发送的文件夹。
Congratulations 🎉 you've built an App that exposes an API. You can use this API to send messages from other services and apps, for example notifying your product's users.恭喜 🎉 你已经构建了一个公开 API 的应用程序。您可以使用此 API 从其他服务和应用程序发送消息,例如通知您产品的用户。
At the end of this tutorial, you will have built an Express App, that exposes an API to send messages via Mailchain. Your API accepts POST requests meaning applications may use your API as a webhook commonly used to trigger notifications. Your app will use the Mailchain SDK to send messages and Bearer tokens to authenticate incoming requests. In most cases, you would add a route to an existing Express App, but for this tutorial, you'll create a new app.在本教程结束时,您将构建一个 Express 应用程序,它公开一个 API 以通过 Mailchain 发送消息。您的 API 接受 POST 请求,这意味着应用程序可以将您的 API 用作通常用于触发通知的 webhook。您的应用程序将使用 Mailchain SDK 发送消息和 Bearer 令牌来验证传入请求。在大多数情况下,您会向现有的 Express 应用添加路由,但对于本教程,您将创建一个新应用。
The existing API we built in the previous guide is unauthenticated, meaning it accepts any valid POST request and sends a message. Passport authenticates the API requests.我们在上一指南中构建的现有 API 未经身份验证,这意味着它接受任何有效的 POST 请求并发送消息。 Passport 对 API 请求进行身份验证。
To install passport and passport-http-bearer libraries and types, open a terminal window and navigate the root directory of your code, then run:要安装 passport 和 passport-http-bearer 库和类型,请打开终端窗口并导航到代码的根目录,然后运行:
passport provides multiple different authentication strategies for APIs and works with Express. passport-http-bearer configures Passport to use the bearer strategy for authentication.passport 为 API 提供了多种不同的身份验证策略,并与 Express 一起工作。 passport-http-bearer 将 Passport 配置为使用承载策略进行身份验证。
Your API will use the bearer authentication scheme to authenticate requests. You'll need to create a list of known tokens and provide them to the application. Passport then looks at the request token and searches for it in the known tokens list.您的 API 将使用承载身份验证方案来验证请求。您需要创建一个已知令牌列表并将它们提供给应用程序。 Passport 然后查看请求令牌并在已知令牌列表中搜索它。
HTTP requests use the Authentication header to send authentication details to the server. Authentication headers specify the method or authentication scheme and credentials. Bearer is an authentication scheme commonly used to authenticate HTTP API requests. The format for a Bearer authentication header is:HTTP 请求使用身份验证标头将身份验证详细信息发送到服务器。身份验证标头指定方法或身份验证方案和凭据。 Bearer 是一种通常用于对 HTTP API 请求进行身份验证的身份验证方案。 Bearer 身份验证标头的格式为:
"Authorization: Bearer {token}"
note笔记
The value of the token can be anything, usually a random generated string that is meaningless to the client. Random values make for easy authentication but since the request is not signed. Care must be taken to properly protect the token as anyone with the token can make requests.令牌的值可以是任何东西,通常是随机生成的对客户端无意义的字符串。随机值有助于轻松进行身份验证,但因为请求未签名。必须注意妥善保护令牌,因为任何拥有令牌的人都可以发出请求。
You need to use a secure random generator to safely generate bearer tokens. The latest version of openssl implements a secure random generator that generates and formats random values of any length.您需要使用安全的随机生成器来安全地生成不记名令牌。最新版本的 openssl 实现了一个安全的随机生成器,可以生成和格式化任意长度的随机值。
Open a terminal window and execute the following command:打开终端窗口并执行以下命令:
openssl rand 32 -hex
Try running it again, notice that each time you run it you get a different unique value.尝试再次运行它,请注意每次运行它都会获得不同的唯一值。
Your app will extract the bearer token from the HTTP request Authorization header. It will then look for the supplied bearer token in a list of known tokens. If it finds a match then the server will authenticate the request.您的应用将从 HTTP 请求授权标头中提取不记名令牌。然后它将在已知令牌列表中查找提供的不记名令牌。如果找到匹配项,则服务器将对请求进行身份验证。
The known tokens are stored in the BEARER_TOKENS environment variable. BEARER_TOKENS is a comma separated list, meaning you can join multiple outputs from generate tokens with commas to create a list of tokens for you API. Paste the following command in your terminal window to quickly generate 3 random tokens separated by commas:已知令牌存储在 BEARER_TOKENS 环境变量中。 BEARER_TOKENS 是一个逗号分隔的列表,这意味着您可以使用逗号连接生成令牌的多个输出,为您的 API 创建一个令牌列表。将以下命令粘贴到您的终端窗口中,以快速生成 3 个以逗号分隔的随机标记:
Open .env.development.local in your editor, and copy the output of the above command to the bottom of the file:在您的编辑器中打开 .env.development.local ,并将上述命令的输出复制到文件底部:
After your .env.development.local should look similar to this:在你的 .env.development.local 应该看起来类似于这样:
SECRET_RECOVERY_PHRASE=enter your secret phrase here BEARER_TOKENS=token-1,token-2,token-3
Your application will use passport to authenticate requests looking for the bearer token.您的应用程序将使用护照来验证寻找不记名令牌的请求。
The new additions to the app.ts code:app.ts 代码的新增内容:
Import passport and passport-http-bearer dependencies.导入 passport 和 passport-http-bearer 依赖项。
Calls initializeAuthentication from the constructor.从构造函数调用 initializeAuthentication。
initializeAuthentication uses the bearer strategy with passport and checks tokens with BEARER_TOKENS environment variable.initializeAuthentication 使用带有护照的承载策略,并使用 BEARER_TOKENS 环境变量检查令牌。
In your editor open the existing app.ts file in the src/ folder. Replace the existing contents by copying and pasting the code below into it.在您的编辑器中打开 src/ 文件夹中的现有 app.ts 文件。通过将下面的代码复制并粘贴到其中来替换现有内容。
Remember to save app.ts after pasting the code.粘贴代码后记得保存app.ts。
Step 5 - Authenticated mail route第 5 步 - 经过身份验证的邮件路由
The existing mail route accepts unauthenticated requests. You'll replace MailRoute with AuthenticatedMailRoute which authenticates requests before sending mails.现有邮件路由接受未经身份验证的请求。您将用 AuthenticatedMailRoute 替换 MailRoute,后者在发送邮件之前对请求进行身份验证。
Sends mails using the same flow as MailRoute使用与 MailRoute 相同的流程发送邮件
Requires Bearer authentication token that passport checks in app.ts需要护照在 app.ts 中检查的 Bearer 身份验证令牌
In your editor open the existing mail.route.ts in the src/routes/ folder. Replacing the existing code, copy and paste the code below into it.在您的编辑器中打开 src/routes/ 文件夹中的现有 mail.route.ts。替换现有代码,将下面的代码复制并粘贴到其中。
Now AuthenticatedMailRoute has replaced MailRoute all that remains is removing MailRoute and adding AuthenticatedMailRoute to the server.现在 AuthenticatedMailRoute 已经替换了 MailRoute,剩下的就是删除 MailRoute 并将 AuthenticatedMailRoute 添加到服务器。
The server code:服务器代码:
Adds routes.添加路由。
Listens to incoming requests.侦听传入请求。
In your editor open the existing server.ts file in the src/ folder. Replace the existing contents by copying and pasting the code below into it.在您的编辑器中打开 src/ 文件夹中的现有 server.ts 文件。通过将下面的代码复制并粘贴到其中来替换现有内容。
You are ready to test your webhook using curl. You'll need to extend the requests from the send API tutorial to include an authentication header.您已准备好使用 curl 测试您的 webhook。您需要扩展发送 API 教程中的请求以包含身份验证标头。
Open a terminal window and navigate to your project root directory, then run:打开一个终端窗口并导航到您的项目根目录,然后运行:
npm run dev
The output should look like:输出应如下所示:
[nodemon] 2.0.20 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): src/**/* .env [nodemon] watching extensions: js,ts,json [nodemon] starting `ts-node -r tsconfig-paths/register --transpile-only src/server.ts` info: ================================= info: ======= ENV: development ======= info: 🚀 App listening on the port 3000 info: =================================
This confirms that the app started correctly and can be accessed via http://localhost:3000.这确认应用程序正确启动并且可以通过 http://localhost:3000 访问。
Now you can start testing your app by sending it HTTP requests.现在您可以通过向其发送 HTTP 请求来开始测试您的应用程序。
The AuthenticatedMailRoute expects a valid Bearer token in the Authorization header.AuthenticatedMailRoute 需要授权标头中的有效 Bearer 令牌。
note笔记
The Authorization header is case-sensitive meaning both the header name and scheme (Bearer) must be supplied with the correct case. The format and casing is:Authorization 标头区分大小写,这意味着标头名称和方案 (Bearer) 都必须提供正确的大小写。格式和大小写为:
Authorization: Bearer {token}授权:不记名 {token}
To get a valid bearer token check .env.development.local for BEARER_TOKENS environment variable, this is a comma separated list of tokens. You can pick any token from the list.要获得有效的持有者令牌,请检查 .env.development.local 中的 BEARER_TOKENS 环境变量,这是一个逗号分隔的令牌列表。您可以从列表中选择任何令牌。
note笔记
If you change BEARER_TOKENS environment variable, you'll need to restart your server. Stop by pressing ctrl+c then start it again.如果更改 BEARER_TOKENS 环境变量,则需要重新启动服务器。按 ctrl+c 停止,然后重新启动。
Use the output from above to populate an authorization header. Edit the command below by replacing {token} with a valid bearer token.使用上面的输出来填充授权标头。通过将 {token} 替换为有效的不记名令牌来编辑以下命令。
Open a terminal window and paste the edited command. After a few seconds, you should get a response that looks a bit like this:打开终端窗口并粘贴编辑的命令。几秒钟后,您应该会收到如下所示的响应:
HTTP/1.1 200 OK Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true ... {"status":"success"}
200 OK means that it worked. 200 is the HTTP response code for success. You can check the message has been sent by looking in the sent folder in the Mailchain web app. Awesome you have sent a Mailchain message using your authenticated webhook.200 OK 表示它有效。 200 是成功的 HTTP 响应代码。您可以通过查看 Mailchain Web 应用程序中的已发送文件夹来检查邮件是否已发送。太棒了,您已经使用经过身份验证的 webhook 发送了 Mailchain 消息。
The following error code and responses will help you troubleshoot:以下错误代码和响应将帮助您排除故障:
Error错误
Error Code错误代码
Possible Issue可能的问题
HTTP/1.1 401 UnauthorizedHTTP/1.1 401 未经授权
401
The authentication is not working:身份验证不起作用: - Check the header response: WWW-Authenticate: Bearer realm="Users", error="..." for clues.- 检查标头响应:WWW-Authenticate: Bearer realm="Users", error="..." 以获取线索。 - Check the Bearer token is correct.- 检查 Bearer 令牌是否正确。 - Check the app.ts code is correct.- 检查 app.ts 代码是否正确。 - Restart the server.- 重新启动服务器。
HTTP/1.1 404 Not FoundHTTP/1.1 404 未找到
404
The API endpoint is not found. Check your mail route.未找到 API 端点。检查您的邮件路由。
Congratulations 🎉 you've extended the send API and added authenticated. You can use this authenticated webhook to send messages from other services and apps, for example notifying your product's users.恭喜 🎉 您已经扩展了发送 API 并添加了身份验证。您可以使用此经过身份验证的 webhook 从其他服务和应用程序发送消息,例如通知您产品的用户。
Try finding where you can use your webhook. Let us know of any interesting integrations or if you need any support via our Discord channel.尝试找到可以使用 webhook 的位置。让我们知道任何有趣的集成,或者您是否需要通过我们的 Discord 频道获得任何支持。
Passport Magic Links with Mailchain带有邮件链的 Passport Magic Links
This tutorial shows you how to create and send ‘login’ Magic links to any EVM-compatible blockchain address, ENS name or Unstoppable domain.本教程向您展示如何创建“登录”Magic 链接并将其发送到任何 EVM 兼容的区块链地址、ENS 名称或 Unstoppable 域。
In this tutorial, you will build a todo list app, complete with functionality that allows users to sign in with Mailchain. By following along with this tutorial, you will learn how to use Passport for passwordless authentication using Mailchain to send magic links.在本教程中,您将构建一个待办事项列表应用程序,其中包含允许用户使用 Mailchain 登录的功能。通过跟随本教程,您将学习如何使用 Passport 进行无密码身份验证,使用 Mailchain 发送魔术链接。
As you work through the tutorial, you'll be using Express as our web framework, along with EJS as our template engine and CSS for styling. You will use SQLite as our database for storing data. Don't worry if you are not familiar with these technologies -- the necessary code will be provided at each step.在学习本教程时,您将使用 Express 作为我们的 Web 框架,同时使用 EJS 作为我们的模板引擎和 CSS 进行样式设置。您将使用 SQLite 作为我们存储数据的数据库。如果您不熟悉这些技术,请不要担心——每个步骤都会提供必要的代码。
A working development environment with Node.js and Git 2. An editor and terminal of your choosing. 3. A Mailchain account for development and testing purposes.使用 Node.js 和 Git 2 的工作开发环境。您选择的编辑器和终端。 3. 用于开发和测试目的的 Mailchain 帐户。
To let users sign in with any valid wallet address, Web3 identity or Mailchain account. For that, you need to create a login page that prompts the user to enter one of these addresses.让用户使用任何有效的钱包地址、Web3 身份或 Mailchain 帐户登录。为此,您需要创建一个登录页面,提示用户输入这些地址之一。
In your terminal, create a file that will contain the authentication-related routes:在您的终端中,创建一个包含身份验证相关路由的文件:
```bash touch routes/auth.js ```
Open the mailchain-tutorial folder in your favorite code editor and navigate to the auth.js file you have just created in routes在您最喜欢的代码编辑器中打开 mailchain-tutorial 文件夹,然后导航到您刚刚在 routes 中创建的 auth.js 文件
In routes/auth.js add the following code, which creates a login route that will render the login page.在 routes/auth.js 中添加以下代码,这将创建一个将呈现登录页面的登录路由。
```js var express = require('express'); var router = express.Router(); router.get('/login', function (req, res, next) { res.render('login'); }); module.exports = router; ```
Now add the route to the app. To do this, open 'app.js' and add the newly created auth route by adding the highlighted code below:现在将路线添加到应用程序。为此,请打开“app.js”并通过添加以下突出显示的代码来添加新创建的身份验证路由:
```js var indexRouter = require('./routes/index'); // highlight-next-line var authRouter = require('./routes/auth'); // require your auth route var app = express(); ```
Now use the authRouter in the app. Below indexRouter, add the following highlighted line:现在在应用程序中使用 authRouter。在 indexRouter 下面,添加以下突出显示的行:
```js app.use('/', indexRouter); // highlight-next-line app.use('/', authRouter); // app should 'use' your auth router ```
Now you will update the login page so the user can enter a Mailchain address. Open the existing login.ejs file in the views folder and add the following highlighted form under the heading:现在您将更新登录页面,以便用户可以输入 Mailchain 地址。打开 views 文件夹中现有的 login.ejs 文件,并在标题下添加以下突出显示的表单:
```html <section class="prompt"> <h3>todos</h3> <h1>Sign in</h1> // highlight-start <form action="/login/mailchain" method="post"> <section> <label for="mailchain_address">Mailchain Address or ENS Name</label> <input id="mailchain_address" name="mailchain_address" type="text" autocomplete="username" placeholder="...@mailchain.com or ensname.eth" required autofocus /> </section> <button type="submit">Sign in with Mailchain</button> </form> // highlight-end <hr /> <p class="help">Don't have an account? <a href="/signup">Sign up</a></p> </section> ```
Restart your app in the terminal (ctrl + c if it's running the run npm start). Click sign in.在终端中重新启动您的应用程序(如果它正在运行 run npm start,则按 ctrl + c)。点击登录。
Excellent! You now have a login page that prompts the user to sign in with a Mailchain address or ENS name.出色的!您现在有一个登录页面,提示用户使用 Mailchain 地址或 ENS 名称登录。
Now you need a way to send Mailchain messages from the app.现在您需要一种从应用程序发送邮件链消息的方法。
For the purposes of this tutorial, you should create a Mailchain account for testing.出于本教程的目的,您应该创建一个用于测试的 Mailchain 帐户。
:::info For a memorable naming scheme, you could append `-test-dev` to your existing account name when you create this test account, i.e. if you already use `alice@mailchain`, create a new account with `alice-test-dev@mailchain` :::
Go to Settings > Secret Recovery Phrase and retrieve the Secret Recovery Phrase for your Mailchain test account. Save it somewhere safe and private.转到设置 > 秘密恢复短语并为您的 Mailchain 测试帐户检索秘密恢复短语。将其保存在安全私密的地方。
Now that you have the Secret Recovery Phrase and a Mailchain address, you should create a file to store it.现在您有了秘密恢复短语和邮件链地址,您应该创建一个文件来存储它。
In your editor create a new file in mailchain-tutorial and label it `.env`. Open the `.env` file and add the following environment variables, setting your `FROM_ADDRESS` to your test account, with the associated`SECRET_RECOVERY_PHRASE`: ```txt # Mailchain Environment Variables FROM_ADDRESS=**user@mailchain.com** SECRET_RECOVERY_PHRASE=**INSERT_SECRET_RECOVERY_PHRASE** ```
You also need to update your database schema to store an authenticating user's Mailchain address and verification status.您还需要更新数据库架构以存储身份验证用户的邮件链地址和验证状态。
Open `'db.js'`and insert the following highlighted lines to the CREATE user statement: ```js db.run("CREATE TABLE IF NOT EXISTS users ( \ id INTEGER PRIMARY KEY, \ username TEXT UNIQUE, \ hashed_password BLOB, \ salt BLOB, \ name TEXT, \ //highlight-start mailchain_address TEXT UNIQUE, \ mailchain_address_verified INTEGER, \ //highlight-end email TEXT UNIQUE, \ email_verified INTEGER \ )"); ```
Now you need to delete the database and re-create it because you have already created the database in previous steps when testing the landing page.现在您需要删除数据库并重新创建它,因为您已经在测试登录页面时在前面的步骤中创建了数据库。
:::danger NOTE: This will delete any data you may have added in this tutorial so far. If you are considering adding this solution to an existing app, you would simply run a DB migration to alter your `users` table. ::: To delete the database, open a new terminal in your editor and run: ```bash rm ./var/db/todos.db ```
Nice work! You're now ready to configure the Passport JS login strategy.干得好!您现在已准备好配置 Passport JS 登录策略。
Now that you've set up Mailchain, you are ready to configure Passport and the passport-magic-linkstrategy.现在您已经设置了 Mailchain,您已准备好配置 Passport 和 passport-magic-linkstrategy。
In the terminal, install the necessary dependencies:在终端中,安装必要的依赖项:
Open auth.js in the routes folder and require the newly installed packages or files as highlighted below:打开 routes 文件夹中的 auth.js 并需要新安装的包或文件,如下突出显示:
```js var express = require('express'); // highlight-start var passport = require('passport'); var MagicLinkStrategy = require('passport-magic-link').Strategy; var Mailchain = require('@mailchain/sdk').Mailchain; var db = require('../db'); // highlight-end var router = express.Router(); ```
Next, in the same file, add the following highlighted code block:接下来,在同一文件中,添加以下突出显示的代码块:
```js var router = express.Router(); // highlight-start var mailchain = Mailchain.fromSecretRecoveryPhrase(process.env.SECRET_RECOVERY_PHRASE); var fromAddress = process.env['FROM_ADDRESS'] || mailchain.user().address; let createMailchainAddress = function (address) { switch (address) { case address.match(/^[\d\w\-\_]*@mailchain\.com$/)?.input: // Mailchain address: return address; case address.match(/^0x[a-fA-F0-9]{40}$/)?.input: // Ethereum address: return address + '@ethereum.mailchain.com'; case address.match(/^.*\.eth$/)?.input: // ENS address: return address + '@ens.mailchain.com'; case address.match(/^.*\.*@mailchain$/)?.input: // Mailchain address without .com: return address + '.com'; default: console.error('Invalid address'); } }; passport.use( new MagicLinkStrategy( { secret: 'keyboard cat', // change this to something secret userFields: ['mailchain_address'], tokenField: 'token', verifyUserAfterToken: true, }, async function send(user, token) { var link = 'http://localhost:3000/login/mailchain/verify?token=' + token; var msg = { to: [createMailchainAddress(user.mailchain_address)], from: fromAddress, subject: 'Sign in to Todos', content: { text: 'Hello! Click the link below to finish signing in to Todos.\r\n\r\n' + link, html: '<h3>Hello!</h3><p>Click the link below to finish signing in to Todos.</p><p><a href="' + link + '">Sign in</a></p>', }, }; return await mailchain.sendMail(msg); }, function verify(user) { return new Promise(function (resolve, reject) { db.get( 'SELECT * FROM users WHERE mailchain_address = ?', [user.mailchain_address], function (err, row) { if (err) { return reject(err); } if (!row) { db.run( 'INSERT INTO users (mailchain_address, mailchain_address_verified) VALUES (?, ?)', [user.mailchain_address, 1], function (err) { if (err) { return reject(err); } var id = this.lastID; var obj = { id: id, mailchain_address: user.mailchain_address, }; return resolve(obj); }, ); } else { return resolve(row); } }, ); }); }, ), ); // highlight-end router.get('/login', function (req, res, next) { res.render('login'); }); ```
The MagicLinkStrategy is now configured. The strategy will sanitize the input address, then send mails containing a magic link using Mailchain. When the user clicks on the magic link, the user record associated with the Mailchain address will be found. If a user record does not exist, one is created the first time someone signs in.现在已配置 MagicLinkStrategy。该策略将清理输入地址,然后使用 Mailchain 发送包含魔法链接的邮件。当用户点击魔术链接时,将找到与 Mailchain 地址关联的用户记录。如果用户记录不存在,则会在有人首次登录时创建一个。
Now that you have prompted the user for their Mailchain address, and have the strategy configured, the next step is to send the user a Mailchain message containing the Magic Link when they click "Sign in with Mailchain.”现在您已提示用户输入他们的 Mailchain 地址,并配置了策略,下一步是在用户单击“使用 Mailchain 登录”时向用户发送包含 Magic Link 的 Mailchain 消息。
You should still be working in the auth.js file in routes but if not, open it now.您应该仍在路由中的 auth.js 文件中工作,但如果没有,请立即打开它。
Add the following route below login route:在登录路由下面添加以下路由:
```js router.get('/login', function (req, res, next) { res.render('login'); }); //highlight-start router.post( '/login/mailchain', passport.authenticate('magiclink', { action: 'requestToken', failureRedirect: '/login', }), function (req, res, next) { res.redirect('/login/mailchain/check'); }, ); //highlight-end module.exports = router; ``` This route will process the form data from the login page and call the `'/login/mailchain/check'` route to send a Mailchain message to that user.
Continuing within auth.js, add the route for '/login/mailchain/check':继续在 auth.js 中,添加“/login/mailchain/check”的路由:
This route will render a page instructing the user to check their Mailchain account and to click the link to authenticate login.此路由将呈现一个页面,指示用户检查其 Mailchain 帐户并单击链接以验证登录。
Now that the application can send the user a Mailchain message with a magic link, the next step is to verify the Mailchain address when they click the link.现在应用程序可以向用户发送带有魔法链接的 Mailchain 消息,下一步是在用户单击该链接时验证 Mailchain 地址。
Within auth.js in your routes section, add this route in the highlighted section below the /login/mailchain/check route:在路由部分的 auth.js 中,将此路由添加到 /login/mailchain/check 路由下方的突出显示部分:
```js router.get('/login/mailchain/check', function (req, res, next) { res.render('login/mailchain/check'); }); // highlight-start router.get( '/login/mailchain/verify', passport.authenticate('magiclink', { successReturnToOrRedirect: '/', failureRedirect: '/login', }), ); // highlight-end ``` This route will verify the Mailchain address when the link is clicked.
Now in the terminal, create a folder and corresponding view for our route, by running the following commands in the terminal:现在在终端中,通过在终端中运行以下命令,为我们的路由创建一个文件夹和相应的视图:
In your code editor, navigate to the file you have just created, (views/login/mailchain/check.ejsand add the following code:在您的代码编辑器中,导航到您刚刚创建的文件(views/login/mailchain/check.ejs 并添加以下代码:
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Express • TodoMVC</title> <link rel="stylesheet" href="/css/base.css" /> <link rel="stylesheet" href="/css/index.css" /> <link rel="stylesheet" href="/css/login.css" /> </head> <body> <section class="prompt"> <h3>todos</h3> <h1>Check your Mailchain Inbox</h1> <p class="instructions"> We sent a magic link to your Mailchain address. Click the link in that message to sign in. </p> <hr /> <p class="help">Didn't receive the message? <a href="/login">Get another link</a></p> </section> <footer class="info"> <p>Created by <a href="https://www.jaredhanson.me">Jared Hanson</a></p> <p>Part of <a href="https://todomvc.com">TodoMVC</a></p> <p> Authentication powered by <a href="https://www.passportjs.org">Passport</a> <br /> & <a href="https://mailchain.com">Mailchain</a> </p> </footer> </body> </html> ```
Now, update views/index.ejs to include the user.mailchain_address field. Change the highlighted the line to match the snippet below:现在,更新 views/index.ejs 以包含 user.mailchain_address 字段。更改突出显示的行以匹配以下代码段:
You have now configured the flow for users to click "Sign in", then enter a Mailchain address or ENS name. When the user clicks "Sign in with Mailchain", the app will send a magic link.您现在已经为用户配置了流程以单击“登录”,然后输入邮件链地址或 ENS 名称。当用户点击“使用 Mailchain 登录”时,应用程序将发送一个魔法链接。
Next you need to be able to establish a login session for an authenticated user.接下来,您需要能够为经过身份验证的用户建立登录会话。
Once you've verified the user's Mailchain address, you need to establish a login session for the user as they navigate the app. To do that, you can add session support.验证用户的 Mailchain 地址后,您需要在用户浏览应用程序时为他们建立登录会话。为此,您可以添加会话支持。
Start by running the following code in the terminal to instal the necessary dependencies:首先在终端中运行以下代码以安装必要的依赖项:
Now you can configure Passport to manage the login session. Open auth.js before the routes section, add the following highlighted code snippet:现在您可以配置 Passport 来管理登录会话。在路由部分之前打开 auth.js,添加以下突出显示的代码片段:
Now try signing in again. In the terminal, run:现在尝试重新登录。在终端中,运行:
```bash npm start ```
Open http://localhost:3000, click "Sign in", enter your Mailchain address or your ENS name and click "Sign in with Mailchain".打开 http://localhost:3000,点击“Sign in”,输入您的 Mailchain 地址或 ENS 名称,然后点击“Sign in with Mailchain”。
Now, check your Mailchain Inbox and click the link.现在,检查您的 Mailchain 收件箱并单击链接。
You are now logged in and should see a screen similar to below! Go ahead and enter some tasks you've been needing to get done. 
Now users can sign in with Mailchain! Next, in the last step of this tutorial, you will add the ability to sign out.现在用户可以使用 Mailchain 登录!接下来,在本教程的最后一步,您将添加注销功能。
Restart your app in the terminal (ctrl + c), then go back to your browser window. You should already be signed in, and can now click "Sign out."在终端 (ctrl + c) 中重新启动您的应用程序,然后返回浏览器窗口。您应该已经登录,现在可以单击“退出”。
Congratulations! You've now got a working app where users can sign in and sign out using Mailchain!恭喜!您现在已经有了一个可用的应用程序,用户可以在其中使用 Mailchain 登录和注销!
Stytch Passwordless Magic Link via Mailchain通过 Mailchain 的 Stytch 无密码魔术链接
At the end of this tutorial, you will have built an Express JS app that sends a passwordless magic link from the Stytch auth platform to the user's wallet address using Mailchain's SDK and protocol.在本教程结束时,您将构建一个 Express JS 应用程序,该应用程序使用 Mailchain 的 SDK 和协议从 Stytch 身份验证平台向用户的钱包地址发送一个无密码的魔法链接。
Stytch supports multiple authentication methods, including the so-called magic link. Magic links work by generating and sending a link with an unique authentication token to an address.Stytch 支持多种身份验证方法,包括所谓的魔术链接。魔术链接的工作原理是生成一个带有唯一身份验证令牌的链接并将其发送到一个地址。
The recipient can prove they own the address by clicking on the link within the message. The link contains an unique and single use authentication token, When a user clicks the Magic Link, the application's authentication service processes and validates the authentication token and creates a user session. For more details and visual representation of the flow, check out Stytch's Email Magic Link overview.收件人可以通过单击消息中的链接来证明他们拥有该地址。该链接包含一个唯一且一次性使用的身份验证令牌,当用户单击 Magic Link 时,应用程序的身份验证服务会处理并验证身份验证令牌并创建用户会话。有关流程的更多详细信息和可视化表示,请查看 Stytch 的 Email Magic Link 概述。
To send messages via Mailchain you need to use Stytch's Embeddable Magic Link. This lets you send magic links via a custom channel.要通过 Mailchain 发送消息,您需要使用 Stytch 的 Embeddable Magic Link。这使您可以通过自定义渠道发送魔术链接。
Since Mailchain requires any registered wallet address to have sign a proof to verify ownership. Applications can build upon that proof, and Mailchain's built-in sender and recipient verification to reliably prove address ownership.
.由于 Mailchain 要求任何注册的钱包地址必须签署证明以验证所有权。应用程序可以基于该证明和 Mailchain 的内置发件人和收件人验证来可靠地证明地址所有权。 .
At the time of writing this tutorial, Stytch offers its Embeddable Magic Link feature on-demand to maintain good security practices.在编写本教程时,Stytch 按需提供其 Embeddable Magic Link 功能以维护良好的安全实践。
You can find out more about this here: Create embeddable magic link, but in summary you need to send a message to support@stytch.com briefly explaining your use case (you can mention this tutorial and send a link). They will provide you with additional security and usage information then enable the feature for you. Requirements around this may change in future.你可以在这里找到更多相关信息:Create embeddable magic link,但总而言之,你需要发送消息到 support@stytch.com 简要说明你的用例(你可以提及本教程并发送链接)。他们将为您提供额外的安全和使用信息,然后为您启用该功能。围绕此的要求将来可能会发生变化。
Step 1 - Clone Stytch Node Magic Link example第 1 步 - 克隆 Stytch 节点 Magic Link 示例
Along with great documentation and quick getting started guides, Stytch offers quick bare-bones examples for multiple platforms with magic link endpoints pre-configured, including an example for Node running an Express JS. Lets start by cloning the repository so we will build on top of it:除了出色的文档和快速入门指南外,Stytch 还为多个平台提供了快速的基本示例,这些平台具有预配置的魔术链接端点,包括运行 Express JS 的 Node 示例。让我们从克隆存储库开始,以便我们在其之上构建:
git clone https://github.com/stytchauth/stytch-node-magic-links cd stytch-node-magic-links
Once the repository has been cloned, install the dependencies by running:克隆存储库后,通过运行以下命令安装依赖项:
npminstall
Stytch is under active development so the Stytch SDK used in the example could be outdated. Install the latest version by running:Stytch 正在积极开发中,因此示例中使用的 Stytch SDK 可能已过时。通过运行安装最新版本:
Navigate to Stytch Dashboard > API Keys. Copy the values for 'Project ID' and 'Secret' and paste them into their corresponding fields in the .env file in the repository you cloned in the previous step.导航到 Stytch 仪表板 > API 密钥。复制“项目 ID”和“机密”的值,并将它们粘贴到您在上一步中克隆的存储库中的 .env 文件中的相应字段中。
Now that we have added some secrets to our '.env' file, we should make sure we do not commit this to our git repository. To stop tracking '.env' in git, run the following command:现在我们已经将一些秘密添加到我们的“.env”文件中,我们应该确保我们不会将其提交到我们的 git 存储库。要停止在 git 中跟踪“.env”,请运行以下命令:
gitrm --cached .env
Add the following line to '.gitignore', then save and close the file:将以下行添加到“.gitignore”,然后保存并关闭文件:
node_modules .env
Now we need to configure a redirect URL in Stytch. This is used once a user is authenticated, so a user can be redirected back to your application. To configure the redirect URL, go to Stytch Dashboard > Redirect URLs and add http://localhost:4567/authenticate then select the type of Login and Sign Up.现在我们需要在 Stytch 中配置一个重定向 URL。一旦用户通过身份验证就会使用它,因此可以将用户重定向回您的应用程序。要配置重定向 URL,请转到 Stytch 仪表板 > 重定向 URL 并添加 http://localhost:4567/authenticate,然后选择登录和注册的类型。
To make sure that everything is working at this point, we can test our app using a traditional email magic link.为确保此时一切正常,我们可以使用传统的电子邮件魔术链接测试我们的应用程序。
To start the app, run:要启动应用程序,请运行:
npm start
In a browser navigate to http://localhost:4567, which should show a page containing a form with an email address field.在浏览器中导航到 http://localhost:4567,它应该显示一个页面,其中包含一个带有电子邮件地址字段的表单。
To verify that email magic link is working, input your traditional (non-Web3) email address. For free tier Stytch accounts without payment card info, it must be on the same domain as the one used for the account. You should be redirected to http://localhost:4567/login_or_create_user, while also receiving email message containing a magic link in your traditional email inbox.要验证电子邮件魔术链接是否有效,请输入您的传统(非 Web3)电子邮件地址。对于没有支付卡信息的免费层级 Stytch 帐户,它必须与用于该帐户的域位于同一域中。您应该被重定向到 http://localhost:4567/login_or_create_user,同时还会在您的传统电子邮件收件箱中收到包含魔术链接的电子邮件。
Clicking on the magic link should open the application in the browser with a welcome message. This means Stytch is setup correctly and you can proceed with the rest of the tutorial.单击魔术链接应在浏览器中打开应用程序并显示欢迎消息。这意味着 Stytch 设置正确,您可以继续本教程的其余部分。
If you have any issues, please trace back through the steps or drop us a line on our Discord server.如果您有任何问题,请追溯这些步骤或在我们的 Discord 服务器上给我们留言。
Configuring the Mailchain SDK is simple. Once the package is installed and configured, it can send Web3 mails via the Mailchain protocol to wallet addresses or other Web3 identities.配置 Mailchain SDK 很简单。安装和配置包后,它可以通过 Mailchain 协议将 Web3 邮件发送到钱包地址或其他 Web3 身份。
To install the Mailchain SDK, stop the application if it is running (hint: CTRL/Control+C on most machines) and run:要安装 Mailchain SDK,请停止正在运行的应用程序(提示:在大多数机器上按 CTRL/Control+C)并运行:
npminstall @mailchain/sdk
Next, open the .env file and insert your Mailchain Secret Recovery Phrase into it. If you don't know your secret recovery phrase, head over to Secret Recovery Phrase Introduction and to learn how to get it from your Mailchain account.接下来,打开 .env 文件并将您的 Mailchain Secret Recovery Phrase 插入其中。如果您不知道您的秘密恢复短语,请前往秘密恢复短语介绍并了解如何从您的 Mailchain 帐户中获取它。
At this point, you need to open stytch-node-magic-links folder in your favorite code editor so you can make changes to the code.此时,您需要在您喜欢的代码编辑器中打开 stytch-node-magic-links 文件夹,以便对代码进行更改。
In the 'server.js' there is pre-configured Express JS application with the routes that we will need for our authentication solution. In summary, we will work mainly on /login_or_create_user route where we will add the Mailchain mail sending logic. All the other routes will remain the same, this includes the /authenticate route that will be responsible for verifying the token from the magic link.在“server.js”中有预配置的 Express JS 应用程序,其中包含我们的身份验证解决方案所需的路由。总之,我们将主要在 /login_or_create_user 路由上工作,我们将在其中添加 Mailchain 邮件发送逻辑。所有其他路由将保持不变,这包括 /authenticate 路由,该路由将负责验证来自魔术链接的令牌。
As mentioned before, our application will work seamlessly with both regular Web2 email addresses and also with the Web3 Mailchain addresses. Lets implement a naive (emphasis on naive) to demonstrate this. All Mailchain addresses, both for Mailchain Accounts and for other Web3 identities such as Ethereum, ENS addresses, will end with mailchain.com, for example alice@mailchain.com or epistola.eth@ens.mailchain.com.如前所述,我们的应用程序将与常规 Web2 电子邮件地址和 Web3 邮件链地址无缝协作。让我们实现一个天真(强调天真)来证明这一点。所有 Mailchain 地址,包括 Mailchain 账户和其他 Web3 身份(如以太坊、ENS 地址),都将以 mailchain.com 结尾,例如 alice@mailchain.com 或 epistola.eth@ens.mailchain.com。
info信息
If you plan on implementing this in your production environment, further validation of Web3 identities and Mailchain addresses is recommended.如果您计划在您的生产环境中实现这一点,建议进一步验证 Web3 身份和邮件链地址。
app.post('/login_or_create_user',asyncfunction(req, res){ const params ={ email: req.body.email, login_magic_link_url: magicLinkUrl, signup_magic_link_url: magicLinkUrl, }; const isMailchain = params.email.endsWith('mailchain.com'); if(isMailchain){ // TODO: Send magic link with Mailchain SDK return; } /* Rest of the code **/ });
Step 5 - Find or create a user by their Mailchain Address第 5 步 - 通过邮件链地址查找或创建用户
In 'server.js', locate the line that invokes the following method:在“server.js”中,找到调用以下方法的行:
This Stytch method is used to send out magic links via traditional emails. When the user inputs an email address that doesn't exist, it will create a new Stytch user and send out a corresponding magic link to that user. Otherwise, when the email is already registered to a user, it will reference the existing user in the magic link. This is useful for providing better context to users. Read more here: Log in or create user by email.这种 Stytch 方法用于通过传统电子邮件发送魔法链接。当用户输入一个不存在的电子邮件地址时,它将创建一个新的 Stytch 用户并向该用户发送一个相应的魔术链接。否则,当电子邮件已经注册到用户时,它将在魔术链接中引用现有用户。这对于为用户提供更好的上下文很有用。在此处阅读更多信息:通过电子邮件登录或创建用户。
We will implement the same behavior for Mailchain addresses. Among other properties, the Stytch User object stores the user email address, which we will use this to store the user's Mailchain address. To make this easier, Stytch offers useful methods for searching existing users and methods for creating new user. We will use these methods and define the field userToAuth that will reference the user that we are going to authenticate.我们将为 Mailchain 地址实现相同的行为。在其他属性中,Stytch User 对象存储用户电子邮件地址,我们将使用它来存储用户的 Mailchain 地址。为了使这更容易,Stytch 提供了用于搜索现有用户的有用方法和用于创建新用户的方法。我们将使用这些方法并定义将引用我们将要进行身份验证的用户的字段 userToAuth。
Add the highlighted code immediately after if (isMailchain) {:在 if (isMailchain) { 之后立即添加突出显示的代码:
Our code now uses await to handle asynchronous requests where it needs to wait for a response. We will add async to our route so it can handle these requests. Replace the route definition with:我们的代码现在使用 await 来处理需要等待响应的异步请求。我们将向我们的路线添加异步,以便它可以处理这些请求。将路由定义替换为:
-app.post('/login_or_create_user', function (req, res) { +app.post('/login_or_create_user', async function (req, res) {
Step 6 - Create the magic link and Mailchain message contents第 6 步 - 创建魔术链接和 Mailchain 消息内容
Now that there is a user object that can support Mailchain addresses for authentication with a magic link, we can now compose the message the user will receive.现在有一个用户对象可以支持使用魔术链接进行身份验证的邮件链地址,我们现在可以编写用户将收到的消息。
As you can see from the snippet, we have defined the subject of the mail we will send out via Mailchain. There is also a magicLinkUrlWithToken that contains the magic link. It will contain value similar to this: http://localhost:4567/authenticate?userId=user-test-60b91433-c79f-41e5-89c8-b8069ba838ef&token=Gy0YNVp22gbPS8icf8tgQ0yxX77IRNyjzJmrdYLbhBv0.从代码片段中可以看出,我们已经定义了将通过 Mailchain 发送的邮件的主题。还有一个包含魔法链接的 magicLinkUrlWithToken。它将包含类似于此的值:http://localhost:4567/authenticate?userId=user-test-60b91433-c79f-41e5-89c8-b8069ba838ef&token=Gy0YNVp22gbPS8icf8tgQ0yxX77IRNyjzJmrdYLbhBv0。
For the mail content, which contains the magic link itself, we will compose a text variant of the content, i.e. a simple plain text message containing just the link, and an html variant of the content with rich text containing a clickable button-style element that navigates to the magic link.对于包含魔术链接本身的邮件内容,我们将组成内容的文本变体,即仅包含链接的简单纯文本消息,以及包含可点击按钮样式元素的富文本内容的 html 变体导航到魔术链接。
With most of the pieces now in place to send the message, we now need to import the Mailchain SDK. Near the beginning of the server.js file, add the following line:现在大部分内容都已准备好发送消息,我们现在需要导入 Mailchain SDK。在 server.js 文件的开头附近,添加以下行:
We also need to configure the Mailchain SDK to use the Secret Recovery Phrase we previously set in our environment variables. The following line should be added immediately after where the client for Stytch is created:我们还需要配置 Mailchain SDK 以使用我们之前在环境变量中设置的 Secret Recovery Phrase。应在创建 Stytch 客户端后立即添加以下行:
And finally, let's configure the Mailchain SDK to send the mail. Scroll down to the route for /login_or_create_user and right below subject and content, replace the following 2 highlighted lines:最后,让我们配置 Mailchain SDK 来发送邮件。向下滚动到 /login_or_create_user 的路径,在主题和内容的正下方,替换以下 2 行突出显示的行:
// TODO: Send Magic Link with Mailchain SDK return;
Now lets repeat same test as we did in Step 2 to verify that it is working correctly, but this time we will use a fully qualified Mailchain address. Mailchain supports many types of Web3 addresses and identities. You can read more about this in address formatting.现在让我们重复与步骤 2 中相同的测试以验证它是否正常工作,但这次我们将使用完全限定的 Mailchain 地址。 Mailchain 支持多种类型的 Web3 地址和身份。您可以在地址格式中阅读更多相关信息。
Start the application by running:通过运行启动应用程序:
npm start
In your browser, navigate to http://localhost:4567. Try by sending magic link to your own Mailchain address (mine is antonio@mailchain.com... feel free to drop me a message 💌⛓️).在您的浏览器中,导航到 http://localhost:4567。尝试将魔法链接发送到您自己的 Mailchain 地址(我的地址是 antonio@mailchain.com...随时给我留言💌⛓️)。
After a few seconds, you should receive the magic link in your Mailchain Inbox 🎉!几秒钟后,您应该会在 Mailchain 收件箱中收到魔法链接 🎉!
Note: if you receive an error in your terminal StytchError: {"status_code":401, ... "error_type":"enterprise_endpoint","error_message":"Thanks for trying Stytch! We're glad you're excited to try our new products, but this one requires approval before using...注意:如果您在终端中收到错误 StytchError: {"status_code":401, ... "error_type":"enterprise_endpoint","error_message":"感谢您尝试 Stytch!我们很高兴您很高兴尝试我们的新产品,但这个需要在使用前获得批准......
Check out prerequisites for instructions on how to request access to the Embeddable Magic Links feature.查看先决条件,了解有关如何请求访问 Embedded Magic Links 功能的说明。
Click on the link to successfully authenticate in your application using Stytch Auth.单击链接以使用 Stytch Auth 在您的应用程序中成功进行身份验证。
The same can be done with an Ethereum address allowing for authentication without requiring the user to directly interact using their wallet (sign any data or send transactions).以太坊地址也可以做到这一点,允许进行身份验证,而无需用户直接使用他们的钱包进行交互(签署任何数据或发送交易)。
Congratulations 🎉, you have now created a passwordless login for Web3 identities, which can work adjacently to your existing authentication flow!恭喜 🎉,您现在已经为 Web3 身份创建了一个无密码登录,它可以与您现有的身份验证流程相邻地工作!
For full working example head over to the forked repository of the original example, stytch-node-magic-links + Mailchain SDK.对于完整的工作示例,请转到原始示例的分支存储库,stytch-node-magic-links + Mailchain SDK。
At the end of this tutorial, we will have built a simple Express App that exposes an API to listen for ethereum address activity (e.g. ERC20, ERC721 and ERC1155 transfer events).在本教程结束时,我们将构建一个简单的 Express 应用程序,它公开一个 API 来侦听以太坊地址活动(例如 ERC20、ERC721 和 ERC1155 传输事件)。
We will be using the Alchemy Notify API quickstart. It provides easy-to-use webhook triggers based on transactions and events, and supports multiple webhook event types. We will use the Address Activity Webhook to send a mail to your ethereum address when a transaction occurs. The code for the webhook is based on the Authenticated webhook tutorial, which is not a prerequisite, but can be helpful to review.我们将使用 Alchemy Notify API 快速入门。它提供基于事务和事件的易于使用的 webhook 触发器,并支持多种 webhook 事件类型。当交易发生时,我们将使用 Address Activity Webhook 向您的以太坊地址发送邮件。 webhook 的代码基于经过身份验证的 webhook 教程,这不是先决条件,但有助于复习。
Ngrok account with Ngrok installed on your machine.在您的计算机上安装了 Ngrok 的 Ngrok 帐户。 Ngrok will be used to expose the localhost to the internet in order to be accessible for the webhook, but feel free to use your own solution (e.g. gitpod.io) to expose the localhost for testing purposes.Ngrok 将用于将 localhost 暴露给 Internet,以便 webhook 可以访问,但您可以随意使用您自己的解决方案(例如 gitpod.io)来暴露 localhost 以进行测试。
To clone the Alchemy webhook examples and navigate into the correct folder, run the following commands in a new terminal:要克隆 Alchemy webhook 示例并导航到正确的文件夹,请在新终端中运行以下命令:
git clone https://github.com/alchemyplatform/webhook-examples.git cd webhook-examples/node-express
Now run yarn in this directory to install all the dependencies.现在在此目录中运行 yarn 以安装所有依赖项。
Navigate to the Notify section in the Alchemy Dashboard.导航到 Alchemy 仪表板中的通知部分。
Run ngrok http 8080 in a terminal window and copy the Forwarding value from the output, it will be something like https://012a-93-12-152-21.eu.ngrok.io. Leave ngrok running so the webhook can be reached by Alchemy Notify.在终端窗口中运行 ngrok http 8080 并从输出中复制转发值,它将类似于 https://012a-93-12-152-21.eu.ngrok.io。让 ngrok 保持运行,以便 Alchemy Notify 可以访问 Webhook。
Under the Address Activity section in Notify Alchemy Dashboard click the + CREATE WEBHOOK button. This will open up a form with some input fields:在 Notify Alchemy Dashboard 的 Address Activity 部分下,单击 + CREATE WEBHOOK 按钮。这将打开一个带有一些输入字段的表单:
Chain: Select Ethereum链:选择以太坊
Network: For testing purposes select Goerli.网络:出于测试目的,选择 Goerli。
Webhook URL: Paste in the Forwarding value from ngrok followed with /webhook-path (ex. https://012a-93-12-152-21.eu.ngrok.io/webhook-path)Webhook URL:粘贴来自 ngrok 的 Forwarding 值,后跟 /webhook-path(例如 https://012a-93-12-152-21.eu.ngrok.io/webhook-path)
Ethereum Addresses: This is the address that will be monitored. Enter the Ethereum address that you have registered to Mailchain and that you want to monitor for events. An Ethereum address will look something like 0xEBaae0531dF65ee3a1623f324C9620bB84c8af8f.以太坊地址:这是将被监控的地址。输入您已注册到 Mailchain 并要监视事件的以太坊地址。以太坊地址类似于 0xEBaae0531dF65ee3a1623f324C9620bB84c8af8f。
Click on the CREATE WEBHOOK to finish creating the web hook.单击 CREATE WEBHOOK 以完成创建 Web 挂钩。
Alchemy signs each webhook requests to prevent un authorized access. In the example app, signatures are validated by the validateAlchemySignature method.Alchemy 对每个 webhook 请求进行签名以防止未经授权的访问。在示例应用程序中,签名由 validateAlchemySignature 方法验证。
To make this example work and validate the signature against the correct key, we need to get the "webhook signing key". Later which we will set this in our application.要使此示例正常运行并根据正确的密钥验证签名,我们需要获取“webhook 签名密钥”。稍后我们将在我们的应用程序中设置它。
To get the "webhook signing key", navigate to the Notify Alchemy Dashboard and scroll down to the webhook and by clicking on the options ⋯ button, then click Signing Key. A box will open with the signing key, it will look something like whsec_EcQnhWcncVkYyda2UgL15kiL.要获取“webhook signing key”,请导航至 Notify Alchemy Dashboard 并向下滚动至 webhook,然后单击选项⋯按钮,然后单击 Signing Key。将打开一个带有签名密钥的框,它看起来类似于 whsec_EcQnhWcncVkYyda2UgL15kiL。
Copy the key and save it somewhere safe. We will use it in the next step of the tutorial.复制密钥并将其保存在安全的地方。我们将在本教程的下一步中使用它。
Step 3 - Configure environment variables and start the application第 3 步 - 配置环境变量并启动应用程序
We need to add some environment variables before we can run our application. Environment variables let you set values that are passed to your server-side code. For development and testing, we can use dotenv and configure environment files in the root directory of the app, named according to the environment, e.g. '.env.development.local'.在运行我们的应用程序之前,我们需要添加一些环境变量。环境变量允许您设置传递给服务器端代码的值。对于开发和测试,我们可以使用dotenv,在app根目录下配置环境文件,根据环境命名,例如'.env.development.local'。
danger危险
Care must be taken to avoid storing environment variables in source control. For this tutorial, there is a .gitignore file. This tells git to ignore each of the existing environment files. This prevents changes to the existing environment files from being stored in git. Make sure you add new environments to .gitignore.必须注意避免在源代码管理中存储环境变量。对于本教程,有一个 .gitignore 文件。这告诉 git 忽略每个现有的环境文件。这可以防止对现有环境文件的更改存储在 git 中。确保将新环境添加到 .gitignore。
As mentioned in the warning above, add the following lines to '.gitignore':.如上面的警告中所述,将以下行添加到“.gitignore”:。
Create a file in the root directory of your app called '.env.development.local' file. Open it in your code editor and include the following values:在您的应用程序的根目录中创建一个名为“.env.development.local”的文件。在代码编辑器中打开它并包含以下值:
Add dotenv as dependency to the app by running:通过运行以下命令将 dotenv 作为依赖项添加到应用程序:
yarnadd dotenv
Instead of the default setup from the Alchemy example, we want our application to use environment variables via dotenv. Open 'src/index.ts' and replace the contents with the following code:我们希望我们的应用程序通过 dotenv 使用环境变量,而不是 Alchemy 示例中的默认设置。打开“src/index.ts”并用以下代码替换内容:
import dotenv from'dotenv'; import express from'express'; import{ addAlchemyContextToRequest, validateAlchemySignature, AlchemyWebhookEvent }from'./webhooksUtil'; dotenv.config({ path:`.env.${process.env.NODE_ENV||'development'}.local`}); asyncfunctionmain():Promise<void>{ const app =express(); const port =Number(process.env.PORT)||8080; const host = process.env.HOST||'127.0.0.1'; const signingKey = process.env.SIGNING_KEY||''; // Middleware needed to validate the alchemy signature app.use( express.json({ verify: addAlchemyContextToRequest, }), ); app.use(validateAlchemySignature(signingKey)); // Register handler for Alchemy Notify webhook events app.post('/webhook-path',(req, res)=>{ const webhookEvent = req.body as AlchemyWebhookEvent; console.log(`Processing webhook event id: ${webhookEvent.id}`); if((webhookEvent.event.eventDetails ='<EVENT_DETAILS>')){ // this is test notification send from Alchemy. Return success. return res.send('Alchemy Notify is the best!'); } }); // Listen to Alchemy Notify webhook events app.listen(port, host,()=>{ console.log(`Example Alchemy Notify app listening at ${host}:${port}`); }); } main();
We can now start our the application by running the following command:我们现在可以通过运行以下命令来启动我们的应用程序:
yarn start
To verify that the webhook is configured properly, go into Alchemy Dahsboard and click the options dropdown of the configured webhook and click the Send Test Notification button.要验证 webhook 是否已正确配置,请进入 Alchemy Dahsboard 并单击已配置 webhook 的选项下拉菜单,然后单击发送测试通知按钮。
If everything is correctly configured, the terminal with ngrok running will show a POST / 200 OK and the terminal running our application will print out something like Processing webhook event id: whevt_s8wrj49yxo19qsoy.如果一切配置正确,运行 ngrok 的终端将显示 POST / 200 OK,并且运行我们应用程序的终端将打印出类似 Processing webhook event id: whevt_s8wrj49yxo19qsoy 的信息。
In src/index.ts you can see an already a configured Express application with route of POST /webhook-path, this route accepts our webhook events. Inside the route there is field called webhookEvent that holds all the event data the app will receive.在 src/index.ts 中,您可以看到一个已经配置好的 Express 应用程序,其路由为 POST /webhook-path,该路由接受我们的 webhook 事件。在路由中有一个名为 webhookEvent 的字段,它包含应用程序将接收的所有事件数据。
Check Alchemy's field definition to understand what data will be sent by this event.检查 Alchemy 的字段定义以了解此事件将发送哪些数据。
To create our Mailchain message we will extract the fromAddress and toAddress. To simplify the example, we will handle only events with category of external that represent the native chain token (e.g. ETH).为了创建我们的邮件链消息,我们将提取 fromAddress 和 toAddress。为了简化示例,我们将仅处理具有代表原生链令牌(例如 ETH)的外部类别的事件。
Next, let's define the mailSubject and mailContent of the mail that we are going to send out with Mailchain.接下来,让我们定义要使用 Mailchain 发送的邮件的 mailSubject 和 mailContent。
Add the following code below the check for test event:在检查测试事件下方添加以下代码:
const webhookEvent = req.body as AlchemyWebhookEvent; console.log(`Processing webhook event id: ${webhookEvent.id}`); if((webhookEvent.event.eventDetails ='<EVENT_DETAILS>')){ // this is test event send from Alchemy. Return success. return res.send('Alchemy Notify is the best!'); } if(webhookEvent.type !=='ADDRESS_ACTIVITY')return res.status(400).send('Only ADDRESS_ACTIVITY event type supported'); for(const activity of webhookEvent.event.activity){ if(activity.category !=='external')continue; const{ fromAddress, toAddress, value, asset, hash }= activity; const mailSubject =`Funds transfer from ${fromAddress} into ${toAddress}`; const mailContent ={ text:`There has been a transfer of ${value}${asset} from ${fromAddress} to ${toAddress}. You can check the transaction details on https://goerli.etherscan.io/tx/${hash}.`, html:`<p>There has been a transfer of <b>${value}${asset}</b> from <b>${fromAddress}</b> into <b>${toAddress}<b>.</p><p>Check the transaction details on <a href="https://goerli.etherscan.io/tx/${hash}">Etherscan</a>.</p>`, }; }
Now we need to install the Mailchain SDK. Stop the application and run the following command:现在我们需要安装 Mailchain SDK。停止应用程序并运行以下命令:
yarnadd @mailchain/sdk
Once @mailchain/sdk is installed restart the application with the yarn start command.安装@mailchain/sdk 后,使用 yarn start 命令重新启动应用程序。
In 'src/index.ts', import the Mailchain SDK and create new instance of it immediately after the assertion of the event type of "const signingKey = ..." in the main function.在“src/index.ts”中,导入 Mailchain SDK 并在主函数中声明事件类型“const signingKey = ...”后立即创建它的新实例。
Step 6 - Send mail with Mailchain SDK第 6 步 - 使用 Mailchain SDK 发送邮件
Now that we have included the mail content and have setup the SDK, sending a mail is very easy. Right after the declaration of the mailSubject and mailContent fields add the following snippet:现在我们已经包含了邮件内容并设置了 SDK,发送邮件非常容易。在 mailSubject 和 mailContent 字段的声明之后添加以下代码段:
For easier async logic, you also need to update the webhook-path route (app.post('/webhook-path)...) and make it an async function. Edit definition to inlude async.为了更简单的异步逻辑,您还需要更新 webhook-path 路由 (app.post('/webhook-path)...) 并使其成为异步函数。编辑定义以包含异步。
This function will send a message both to the fromAddress and toAddress address of the token transfer. For simplicity of the example there is no logic to only send mail to the monitored addresses by the webhook. A solution to send mail only to monitored address would include cross-checking the addresses against the Alchemy SDK returning the addresses for the configured webhook.此函数将向令牌传输的 fromAddress 和 toAddress 地址发送一条消息。为了示例的简单性,没有逻辑仅将邮件发送到 webhook 监控的地址。仅向受监控地址发送邮件的解决方案包括根据 Alchemy SDK 返回已配置 webhook 地址的地址进行交叉检查。
Step 7 - Faucet some funds into your address and test it out第 7 步 - 将一些资金注入您的地址并进行测试
In order not to transfer real ETH on mainnet, we are using the Goerli testnet. For these testnets you can request some free funds to be added to your address, for Goerli this is done via https://goerlifaucet.com/. Just input your address into the field and get some free test tokens.为了不在主网上转移真实的 ETH,我们使用歌尔力测试网。对于这些测试网,您可以请求将一些免费资金添加到您的地址,对于 Goerli,这是通过 https://goerlifaucet.com/ 完成的。只需在字段中输入您的地址,即可获得一些免费的测试代币。
This transfer is going to actually fire up a event by the webhook since we are transferring funds to our monitored address. Go on and check your Mailchain mailbox for new messages on https://app.mailchain.com.由于我们正在将资金转移到我们的监控地址,因此该转账实际上将通过 webhook 触发一个事件。继续并在 https://app.mailchain.com 上检查您的 Mailchain 邮箱是否有新消息。
To further test this, you can make small transfers between your Ethereum accounts. Make sure you have selected Goerli testnet on your wallet before making the transfers.为了进一步测试这一点,您可以在您的以太坊账户之间进行小额转账。在进行转账之前,请确保您已经在钱包中选择了 Goerli testnet。
Congratulations 🎉 you've built an awesome App that can notify you or your users of changes of their address funds.恭喜 🎉 你已经构建了一个很棒的应用程序,可以通知你或你的用户地址资金的变化。
As mentioned before Alchemy has an API and SDK for JS that can be used to create, update and remove Notify webhooks. This is very useful if we want to make a meaningful implementation that is not used just for testing. You can access the Alchemy SDK Quickstart to get started and learn more.如前所述,Alchemy 有一个适用于 JS 的 API 和 SDK,可用于创建、更新和删除 Notify webhook。如果我们想要进行有意义的实现而不只是用于测试,这将非常有用。您可以访问 Alchemy SDK 快速入门以开始使用并了解更多信息。
On top of this, checkout more generic approach of webhooks with authenticated webhook guide. Let us know of any interesting variations of this tutorial that you have made or if you need any support via our Discord channel.最重要的是,使用经过身份验证的 webhook 指南检查更通用的 webhook 方法。让我们知道您对本教程所做的任何有趣的修改,或者您是否需要通过我们的 Discord 频道获得任何支持。
This tutorial shows you how to send HAL notifications via an authenticated Mailchain webhook to any EVM-address, ENS name or Unstoppable domain.本教程向您展示如何通过经过身份验证的 Mailchain webhook 将 HAL 通知发送到任何 EVM 地址、ENS 名称或 Unstoppable 域。
At the end of this tutorial, you will have built an Express App, that exposes an API to send HAL notifications via Mailchain to any EVM-address, ENS name or Unstoppable domain. You will create on-chain event notifications in HAL Notify, and configure HAL to use your API as a webhook for sending POST requests to. Your app will use the Mailchain SDK to send the notifications and Bearer tokens to authenticate incoming requests. In most cases, you would add a route to an existing Express App, but for this tutorial, you'll create a new app.在本教程结束时,您将构建一个 Express 应用程序,它公开一个 API 以通过邮件链将 HAL 通知发送到任何 EVM 地址、ENS 名称或 Unstoppable 域。您将在 HAL Notify 中创建链上事件通知,并将 HAL 配置为将您的 API 用作向其发送 POST 请求的 Webhook。您的应用程序将使用 Mailchain SDK 发送通知和 Bearer 令牌来验证传入请求。在大多数情况下,您会向现有的 Express 应用添加路由,但对于本教程,您将创建一个新应用。
Ngrok account with Ngrok installed on your machine. Ngrok will be used to expose the localhost to the internet in order to be accessible for the webhook, but feel free to use your own solution (e.g. gitpod.io) to expose the localhost for testing purposes.在您的计算机上安装了 Ngrok 的 Ngrok 帐户。 Ngrok 将用于将 localhost 暴露给 Internet,以便 webhook 可以访问,但您可以随意使用您自己的解决方案(例如 gitpod.io)来暴露 localhost 以进行测试。
You'll create a new Express app that exposes an API, the simplest way to do that is with a generator that creates an Express App structure. There are various express generators, for this tutorial you'll use typescript-express-starter.您将创建一个公开 API 的新 Express 应用程序,最简单的方法是使用创建 Express 应用程序结构的生成器。有多种快速生成器,对于本教程,您将使用 typescript-express-starter。
To begin, open a terminal window on your computer and run:首先,在您的计算机上打开一个终端窗口并运行:
typescript-express-starter will ask you for some details:typescript-express-starter 会要求您提供一些详细信息:
Accept the default template, by pressing enter.按 Enter 键接受默认模板。
Press n when asked to update to the latest packages, this guarantees this tutorial completes successfully.当要求更新到最新包时按 n,这保证本教程成功完成。
Press y when asked to removed duplicate packages at npm.当要求删除 npm 上的重复包时按 y。
typescript-express-starter can take a while to create a new project as it's installing npm packages. Once completed typescript-express-starter will confirm it's status:typescript-express-starter 在安装 npm 包时可能需要一些时间来创建新项目。完成后,typescript-express-starter 将确认其状态:
?Please select the template you want default ?Do you want to update all packages in the node_modules directory and dependency ?No ?Do you want to Used to removed duplicate packages at npm ?Yes [1/3] 🔍 copying project... [2/3] 🚚 fetching node_modules... [3/3] 🔗 linking node_modules... ───────────────────────────────────────── ✔ Complete setup project
Your Express App is now created.您的 Express 应用现已创建。
Check you can start your mailchain-hal-webhook app in development mode by running:通过运行以下命令检查您是否可以在开发模式下启动您的 mailchain-hal-webhook 应用程序:
cd mailchain-hal-webhook && npm run dev
The output should look like:输出应如下所示:
[nodemon]2.0.20 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): src/**/*.env [nodemon] watching extensions: js,ts,json [nodemon] starting `ts-node -r tsconfig-paths/register --transpile-only src/server.ts` info:================================= info:=======ENV: development ======= info: 🚀 App listening on the port 3000 info:=================================
This confirms that the app started correctly and can be accessed via http://localhost:3000.这确认应用程序正确启动并且可以通过 http://localhost:3000 访问。
Press ctrl+c, this will stop the Express App.按 ctrl+c,这将停止 Express 应用程序。
Mailchain SDK is the easiest way to use Mailchain, it deals with all of the cryptography details for you.Mailchain SDK 是使用 Mailchain 的最简单方法,它为您处理所有密码学细节。
To install the Mailchain SDK you need to run an npm command in the base directory of your project mailchain-hal-webhook. If you are following Step 1, you should already be in this folder. Otherwise, open up a terminal window and navigate to your mailchain-hal-webhook folder.要安装 Mailchain SDK,您需要在项目 mailchain-hal-webhook 的基本目录中运行 npm 命令。如果您正在执行第 1 步,则您应该已经位于该文件夹中。否则,打开一个终端窗口并导航到您的 mailchain-hal-webhook 文件夹。
Install Mailchain SDK using npm:使用 npm 安装 Mailchain SDK:
npm install --save @mailchain/sdk
You have now installed the Mailchain SDK and are ready to configure it.您现在已经安装了 Mailchain SDK 并准备好对其进行配置。
Open mailchain-hal-webhook in your favorite code editor. You'll see it contains example services, controllers, routes, etc. Later you'll extend this functionality.在您喜欢的代码编辑器中打开 mailchain-hal-webhook。您会看到它包含示例服务、控制器、路由等。稍后您将扩展此功能。
The Mailchain SDK needs to be authenticated with your Secret Recovery Phrase to send messages.Mailchain SDK 需要使用您的 Secret Recovery Phrase 进行身份验证才能发送消息。
Get the Secret Recovery Phrase for your test and development Mailchain account.为您的测试和开发 Mailchain 帐户获取秘密恢复短语。
Open .env.development.local in your editor, and add a new line to the bottom SECRET_RECOVERY_PHRASE=enter your secret phrase here.在您的编辑器中打开 .env.development.local,并在底部添加一个新行 SECRET_RECOVERY_PHRASE=在此处输入您的密码。
Replace enter your secret phrase here with your Secret Recovery Phrase and save the file.用您的秘密恢复短语替换在这里输入您的秘密短语并保存文件。
After your .env.development.local should look similar to this:在您的 .env.development.local 看起来应该与此类似:
# PORT PORT=3000 SECRET_RECOVERY_PHRASE=enter your secret phrase here
In your terminal window run, npm run dev from the root directory of your mailchain-hal-webhook app. You should get a response similar to below:在您的终端窗口运行中,从您的 mailchain-hal-webhook 应用程序的根目录运行 npm dev。您应该会得到类似于以下的响应:
info:================================= info:=======ENV: development ======= info: 🚀 App listening on the port 3000 info:=================================
This means is successfully started and listening on port 3000.这意味着已成功启动并侦听端口 3000。
info信息
NOTE: nodemon automatically restarts your API when file changes are detected. However, it doesn't pick up changes to .env.development.local so you need to restart the server manually by pressing ctrl + c and running npm run dev. You'll only need to restart the app when changing the SECRET_RECOVERY_PHRASE setting.注意:nodemon 会在检测到文件更改时自动重启您的 API。但是,它不会获取对 .env.development.local 的更改,因此您需要通过按 ctrl + c 并运行 npm run dev 来手动重启服务器。您只需在更改 SECRET_RECOVERY_PHRASE 设置时重新启动应用程序。
1.3. Create a service for sending mail1.3.创建发送邮件的服务
Express uses services to perform tasks, in this case sending mail using the Mailchain SDK. The service will send messages using the account based on the SECRET_RECOVERY_PHRASE environment variable.Express 使用服务来执行任务,在本例中使用 Mailchain SDK 发送邮件。该服务将使用基于 SECRET_RECOVERY_PHRASE 环境变量的帐户发送消息。
MailService will perform the following actions:MailService 将执行以下操作:
Initialize the Mailchain SDK using the SECRET_RECOVERY_PHRASE.使用 SECRET_RECOVERY_PHRASE 初始化 Mailchain SDK。
Set the from address to the currently authenticated user.将发件人地址设置为当前经过身份验证的用户。
Send mail using the Mailchain SDK.使用 Mailchain SDK 发送邮件。
Inside src/services/ create mail.service.ts and copy the code below into it.在 src/services/ 中创建 mail.service.ts 并将下面的代码复制到其中。
Change the to: to the address or addresses you want to receive the notifications, making sure you use the fully qualified mailchain address, for example:将 to: 更改为您要接收通知的一个或多个地址,确保使用完全限定的邮件链地址,例如:
import{Mailchain,SendMailParams,SendMailResult}from'@mailchain/sdk'; classMailService{ asyncsend(params:SendMailParams):Promise<SendMailResult>{ // use the environment variable to provide your secret recovery phrase const secretRecoveryPhrase = process.env.SECRET_RECOVERY_PHRASE; if(secretRecoveryPhrase ==null){ thrownewError('You must provide a secret recovery phrase'); } const mailchain =Mailchain.fromSecretRecoveryPhrase(secretRecoveryPhrase); if(!params.from|| params.from===''){ // set the from address to current user if not provided const currentUser =await mailchain.user(); params.from= currentUser.address; } returnawait mailchain.sendMail(params); } asynchalWebhook(params){ const msg ={ to:['mishadv.eth@ens.mailchain.com'], from: params.from, subject:'Hal Notification', content:{ text: params['Body'], html:'<div>'+ params['Body']+'</div>', }, }; returnawaitthis.send(msg); } } exportdefaultMailService;
Remember to save mail.service.ts after pasting the code.粘贴代码后记得保存 mail.service.ts。
Controllers manage the incoming HTTP requests and send the necessary data to the correct service.控制器管理传入的 HTTP 请求并将必要的数据发送到正确的服务。
MailController will perform the following actions:MailController 将执行以下操作:
Pass the HTTP request body to the send service.将 HTTP 请求正文传递给发送服务。
Return a response to the request with the status field from the Mailchain SDK send result.使用 Mailchain SDK 发送结果中的状态字段返回对请求的响应。
In your editor create mail.controller.ts in the src/controllers/ folder. Copy and paste the code below into it.在您的编辑器中,在 src/controllers/ 文件夹中创建 mail.controller.ts。将下面的代码复制并粘贴到其中。
Passport authenticates API requests. In this case Passport will authenticate whether a POST request has come from HAL.Passport 验证 API 请求。在这种情况下,Passport 将验证 POST 请求是否来自 HAL。
To install passport and passport-http-bearer libraries and types, open a terminal window and navigate to the root directory of your code, then run:要安装 passport 和 passport-http-bearer 库和类型,请打开终端窗口并导航到代码的根目录,然后运行:
passport provides multiple different authentication strategies for APIs and works with Express. passport-http-bearer configures Passport to use the bearer strategy for authentication.passport 为 API 提供多种不同的身份验证策略,并与 Express 一起使用。 passport-http-bearer 将 Passport 配置为使用承载策略进行身份验证。
Your API will use the bearer authentication scheme to authenticate requests. You'll need to create a list of known tokens and provide them to the application. Passport then looks at the request token and searches for it in the known tokens list.您的 API 将使用承载身份验证方案来验证请求。您需要创建一个已知令牌列表并将它们提供给应用程序。 Passport 然后查看请求令牌并在已知令牌列表中搜索它。
The format for a Bearer authentication header is:不记名身份验证标头的格式为:
"Authorization: Bearer {token}"
info信息
NOTE: The value of the token can be anything, usually a random generated string that is meaningless to the client. Random values make for easy authentication but since the request is not signed. Care must be taken to properly protect the token as anyone with the token can make requests.注意:令牌的值可以是任何东西,通常是随机生成的对客户端无意义的字符串。随机值有助于轻松进行身份验证,但因为请求未签名。必须注意妥善保护令牌,因为任何拥有令牌的人都可以发出请求。
You need to use a secure random generator to safely generate bearer tokens. The latest version of openssl implements a secure random generator that generates and formats random values of any length.您需要使用安全的随机生成器来安全地生成不记名令牌。最新版本的 openssl 实现了一个安全的随机生成器,可以生成和格式化任意长度的随机值。
Open a terminal window and execute the following command:打开终端窗口并执行以下命令:
openssl rand 32 -hex
Try running it again, notice that each time you run it you get a different unique value.尝试再次运行它,请注意每次运行它都会获得不同的唯一值。
Your app will extract the bearer token from the HTTP request Authorization header. It will then look for the supplied bearer token in a list of known tokens. If it finds a match then the server will authenticate the request.您的应用将从 HTTP 请求授权标头中提取不记名令牌。然后它将在已知令牌列表中查找提供的不记名令牌。如果找到匹配项,则服务器将对请求进行身份验证。
The known tokens are stored in the BEARER_TOKENS environment variable. BEARER_TOKENS is a comma separated list, meaning you can join multiple outputs from generate tokens with commas to create a list of tokens for you API. Paste the following command in your terminal window to quickly generate 3 random tokens separated by commas:已知令牌存储在 BEARER_TOKENS 环境变量中。 BEARER_TOKENS 是一个逗号分隔的列表,这意味着您可以使用逗号连接生成令牌的多个输出,为您的 API 创建令牌列表。将以下命令粘贴到您的终端窗口中,以快速生成 3 个以逗号分隔的随机标记:
Open .env.development.local in your editor, and copy the output of the above command to the bottom of the file:在您的编辑器中打开 .env.development.local ,并将上述命令的输出复制到文件底部:
After your .env.development.local should look similar to this:在您的 .env.development.local 看起来应该与此类似:
SECRET_RECOVERY_PHRASE=enter your secret phrase here BEARER_TOKENS=token-1,token-2,token-3
Your application will use passport to authenticate requests looking for the bearer token.您的应用程序将使用护照来验证寻找不记名令牌的请求。
The new additions to the app.ts code:app.ts 代码的新增内容:
Import passport and passport-http-bearer dependencies.导入 passport 和 passport-http-bearer 依赖项。
Calls initializeAuthentication from the constructor.从构造函数调用 initializeAuthentication。
initializeAuthentication uses the bearer strategy with passport and checks tokens with BEARER_TOKENS environment variable.initializeAuthentication 将承载策略与护照结合使用,并使用 BEARER_TOKENS 环境变量检查令牌。
In your editor open the existing app.ts file in the src/ folder. Replace the existing contents by copying and pasting the code below into it.在您的编辑器中打开 src/ 文件夹中的现有 app.ts 文件。通过将下面的代码复制并粘贴到其中来替换现有内容。
RESTful API's are designed around paths and methods, in Express these are created in the src/routes folder.RESTful API 是围绕路径和方法设计的,在 Express 中,这些是在 src/routes 文件夹中创建的。
The API is called by clients using HTTP. The HTTP interface is modeled as a RESTful API making it familiar for developers and easy to discover.API 由使用 HTTP 的客户端调用。 HTTP 接口被建模为 RESTful API,使开发人员熟悉并且易于发现。
You'll create an additional HAL webhook route that accepts HAL notification parameters. The route will use the sendMailfunction you created above.您将创建一个额外的 HAL webhook 路由来接受 HAL 通知参数。该路由将使用您在上面创建的 sendMail 函数。
3.1. Create HAL webhook route3.1.创建 HAL webhook 路由
halWebhookRoute performs the following actions:halWebhookRoute 执行以下操作:
Adds the send path.添加发送路径。
Listens for a POST.侦听 POST。
Route request to the mail controller.将请求路由到邮件控制器。
In your editor create halwebhook.route.tsin the src/routes/ folder. Copy and paste the code below into it.在您的编辑器中,在 src/routes/ 文件夹中创建 halwebhook.route.ts。将下面的代码复制并粘贴到其中。
Now HalWebhookRoute has been created, the final code change is to add HalWebhookRoute to the server.现在 HalWebhookRoute 已经创建,最后的代码更改是将 HalWebhookRoute 添加到服务器。
The server code:服务器代码:
Adds routes.添加路由。
Listens to incoming requests.侦听传入请求。
In your editor open the existing server.ts file in the src/ folder. Replace the existing contents by copying and pasting the code below into it.在您的编辑器中打开 src/ 文件夹中的现有 server.ts 文件。通过将下面的代码复制并粘贴到其中来替换现有内容。
Run ngrok http 3000 in a terminal and copy the Forwarding value from the output, it will be something like https://012a-93-12-152-21.eu.ngrok.io. Leave it running so the webhook can be reached by HAL notify.在终端中运行 ngrok http 3000 并从输出中复制转发值,它类似于 https://012a-93-12-152-21.eu.ngrok.io。让它保持运行,以便 HAL 通知可以访问 webhook。
Webhook URL: Copy the Forwarding value from ngrok and add the route /hal-webhook to the end of it. It should look something like:Webhook URL:从 ngrok 复制 Forwarding 值并将路由 /hal-webhook 添加到它的末尾。它应该看起来像:
https://012a-93-12-152-21.eu.ngrok.io/hal-webhook
Step 5: Create your notification path in HAL第 5 步:在 HAL 中创建您的通知路径
HAL provides no-code web3 infrastructure. HAL Notify makes it easy to implement web3 notifications which can be triggered by any EVM state change, smart contract, wallet and more. HAL supports multiple channels for receiving notifications, including sending to webhooks. In this case, HAL will use your API as a webhook and we will get the public endpoint from gitpod.HAL 提供无代码 web3 基础设施。 HAL Notify 可以轻松实现 web3 通知,这些通知可以由任何 EVM 状态更改、智能合约、钱包等触发。 HAL 支持多个接收通知的渠道,包括发送到 webhook。在这种情况下,HAL 将使用您的 API 作为 webhook,我们将从 gitpod 获取公共端点。
5.1. Configure your notifications in the HAL app5.1.在 HAL 应用程序中配置您的通知
Create an account or login to https://app.hal.xyz/ and create a new workspace for your Mailchain notification path.创建一个帐户或登录到 https://app.hal.xyz/ 并为您的 Mailchain 通知路径创建一个新的工作区。
In the workspace, click ‘Create Notification’在工作区中,单击“创建通知”
Choose notification triggers选择通知触发器
HAL provides a number of different triggers you can choose from, including base fee tracking, token purchase tracking and NFT floor price. For this example, we will trigger when Ethereum Base Fee is Above 0 Gwei, as this will give us a near-instant notification.HAL 提供了多种不同的触发器供您选择,包括基本费用跟踪、代币购买跟踪和 NFT 底价。对于这个例子,我们将在以太坊基础费用高于 0 Gwei 时触发,因为这将给我们一个近乎即时的通知。
Connect webhook连接网络钩子
Select the Action ‘Webhook: Send a POST request’.选择操作“Webhook:发送 POST 请求”。
Copy in the endpoint address with route that you created in the previous step.使用您在上一步中创建的路由复制端点地址。
Select Add Header:选择添加标题:
Header name: ‘Authorisation’标头名称:“授权”
Value: Bearer token_1 (Bearer followed by one of the tokens you copied into env.development.local)值:Bearer token_1(Bearer 后跟您复制到 env.development.local 的令牌之一)
This tutorial shows you how to integrate Tenderly Alerts which can trigger notifications for on-chain events and send them directly to an EVM address, ENS name or Unstoppable domain via Mailchain.本教程向您展示如何集成 Tenderly Alerts,它可以触发链上事件的通知,并通过 Mailchain 将它们直接发送到 EVM 地址、ENS 名称或 Unstoppable 域。
Tenderly Alerting listens for events on the blockchain and sends real-time notifications to your desired destination when the event occurs. With Tenderly Alerting, you can stay informed about desired or undesired events related to transitions, wallets, smart contracts, or any other activity on the network.Tenderly Alerting 监听区块链上的事件,并在事件发生时将实时通知发送到您想要的目的地。通过 Tenderly Alerting,您可以随时了解与转换、钱包、智能合约或网络上任何其他活动相关的所需或不需要的事件。
Mailchain is the communication layer for Web3. With Mailchain, people can communicate using their Web3 identities through a private, end-to-end encrypted mail experience. The open source Mailchain SDK provides a way for developers to integrate using patterns that easily recompose, adapt, and extend.Mailchain 是 Web3 的通信层。借助 Mailchain,人们可以通过私有的、端到端的加密邮件体验使用他们的 Web3 身份进行通信。开源 Mailchain SDK 为开发人员提供了一种使用易于重构、调整和扩展的模式进行集成的方法。
Tutorial: Create a Tenderly Webhook教程:创建 Tenderly Webhook
In this tutorial we’ll use a simple Express App that exposes an API webhook that can be called based on on-chain events. We will be using Tenderly, which can deliver alerts based on simple or advanced triggers from transactions and events.在本教程中,我们将使用一个简单的 Express 应用程序,它公开了一个可以根据链上事件调用的 API webhook。我们将使用 Tenderly,它可以根据来自交易和事件的简单或高级触发器提供警报。
This demonstrates how to setup the webhook that can deliver alerts for use cases including: balance changes, user receipts for NFT purchases, welcome messages, alerting your team of failed transactions and more.这演示了如何设置可以为用例发送警报的 webhook,包括:余额变化、NFT 购买的用户收据、欢迎消息、提醒您的团队交易失败等等。
Prerequisites先决条件
To complete this tutorial, you need to first:要完成本教程,您首先需要:
Ngrok account with Ngrok installed on your machine. Ngrok will be used to expose the localhost to the internet in order to be accessible for the webhook. If you prefer to use your own solution to expose localhost to the internet for testing purposes, feel free.在您的计算机上安装了 Ngrok 的 Ngrok 帐户。 Ngrok 将用于将 localhost 暴露给 Internet,以便 webhook 可以访问。如果您更喜欢使用自己的解决方案将 localhost 公开到 Internet 以进行测试,请随意。
Step 1 - Set up the Express JS API service第 1 步 - 设置 Express JS API 服务
Start by creating and navigating to a new directory, then initialize the app with npm:首先创建并导航到一个新目录,然后使用 npm 初始化应用程序:
mkdir mailchain-tenderly-example cd mailchain-tenderly-example
Create a file called 'server.js':创建一个名为“server.js”的文件:
touch server.js
Paste in the following code into 'server.js'. This code is based on code provided in Tenderly's webhook configuration page under Advanced Options:将以下代码粘贴到“server.js”中。此代码基于高级选项下 Tenderly 的 webhook 配置页面中提供的代码:
// server.js // // Use this sample code to handle webhook events // 1) Paste this code into a new file (server.js) // // 2) npm init // // 3) Install dependencies // npm install --save express // npm install --save crypto // // 4) Run the server on http://localhost:8008 // npm start (start script in package.json must point to server.js) const express =require('express'); const crypto =require('crypto'); const app =express(); // replace this with key taken from dashboard for specific webhook // if you are testing webhook before creation set it on empty string const signingKey =''; app.get('/webhook',(req, res)=>{ res.send('ok'); }); app.post('/webhook', express.raw({type:'application/json'}),(request, response)=>{ const signature = request.headers['x-tenderly-signature']; const timestamp = request.headers['date']; if(!isValidSignature(signature, request.body, timestamp)){ response.status(400).send('Webhook signature not valid'); return; } let body; try{ body =JSON.parse(request.body.toString()); }catch(e){ response.status(400).send('Webhook error: ', e); return; } const eventType = body.event_type; switch(eventType){ case'TEST': // Then define and call a function to handle the test event break; case'ALERT': // Then define and call a function to handle the alert event break; // ... handle other event types default: console.log('Unhandled event type ', eventType); } // Return a 200 response response.send(); }); const port =8008; app.listen(port,()=>console.log('Running on port ', port)); functionisValidSignature(signature, body, timestamp){ const hmac = crypto.createHmac('sha256', signingKey);// Create a HMAC SHA256 hash using the signing key hmac.update(body.toString(),'utf8');// Update the hash with the request body using utf8 hmac.update(timestamp);// Update the hash with the request timestamp const digest = hmac.digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature),Buffer.from(digest)); }
Initialize npm by running this command通过运行此命令来初始化 npm
npm init
You can accept all the defaults similar to the picture below, but make sure the entry point is server.js:您可以接受类似于下图的所有默认值,但要确保入口点是 server.js:
Then start the application, which calls the 'server.js' file as defined in the 'package.json' file that npm generated for us.然后启动应用程序,它调用 npm 为我们生成的“package.json”文件中定义的“server.js”文件。
npm start
The terminal should output that the express server is running on port 8008终端应该输出 express 服务器正在端口 8008 上运行
Step 2 - Make our local webhook publicly accessible第 2 步 - 使我们的本地 webhook 可公开访问
We are running this tutorial in a local environment. Tenderly will need to access our endpoint but because it is on our local network, it cannot be accessed from the Internet.我们在本地环境中运行本教程。 Tenderly 需要访问我们的端点,但因为它在我们的本地网络上,所以无法从 Internet 访问它。
Ngrok can be used to expose the localhost to the internet in order for it to be accessible to the webhook. You may prefer to use your own solution to expose localhost to the internet for testing purposes. Alternatively, there are browser-based development environments that can also publicly expose a running service (e.g. Gitpod).Ngrok 可用于将 localhost 暴露给 Internet,以便 webhook 可以访问它。您可能更愿意使用自己的解决方案将 localhost 公开到 Internet 以进行测试。或者,有基于浏览器的开发环境也可以公开公开正在运行的服务(例如 Gitpod)。
To start Ngrok, run the following command in a new terminal window:要启动 Ngrok,请在新的终端窗口中运行以下命令:
ngrok http 8008
Copy the Forwarding value from the output, it will be something like https://012a-93-12-152-21.eu.ngrok.io and leave the service running so the webhook can be reached by Tenderly.从输出中复制 Forwarding 值,类似于 https://012a-93-12-152-21.eu.ngrok.io 并保持服务运行,以便 Tenderly 可以访问 webhook。
danger危险
If you stop Ngrok at any time, you may need to reconfigure the forwarding value in your Tenderly webhook when you restart it.如果您随时停止 Ngrok,您可能需要在重新启动 Tenderly webhook 时重新配置转发值。
Now that we have a destination endpoint that can be reached publicly, we can configure Tenderly to reach the destination:现在我们有一个可以公开到达的目标端点,我们可以配置 Tenderly 到达目的地:
Go to your Tenderly Dashboard转到您的 Tenderly 仪表板
Choose Alerts > Destinations (note: you will need to add a wallet address to monitor if this is your first time using Tenderly)选择 Alerts > Destinations(注意:如果这是你第一次使用 Tenderly,你需要添加一个钱包地址来监控)
Next, select Webhook from the Add Destination section:接下来,从“添加目标”部分选择 Webhook:
Enter your webhook details, including the Ngrok URL with the correct endpoint (e.g. [https://012a-93-12-152-21.eu.ngrok.io/webhook](https://91f2-80-76-122-194.eu.ngrok.io)) as the Webhook URL输入您的 webhook 详细信息,包括具有正确端点的 Ngrok URL(例如 [https://012a-93-12-152-21.eu.ngrok.io/webhook](https://91f2-80-76-122 -194.eu.ngrok.io)) 作为 Webhook URL
Test the webhook by clicking ‘Send test webhook’. Assuming it is successful, click ‘Add webhook’.通过单击“发送测试 webhook”来测试 webhook。假设成功,请单击“添加 webhook”。
Under the Active Destinations section, choose the destination you just created, and click the button for more details在 Active Destinations 部分下,选择您刚刚创建的目的地,然后单击按钮了解更多详细信息
Copy the Signing Secret and store this somewhere private and safe. We will use it in the next section.复制 Signing Secret 并将其存储在私密且安全的地方。我们将在下一节中使用它。
Step 4 - Configure environment variables and start the application第 4 步 - 配置环境变量并启动应用程序
We now need to add some secrets and settings to our application. Environment variables let you set values that are passed to your server-side code. For development and testing, we can use dotenv and configure environment files in the root directory of the app, named according to the environment, e.g. '.env.development.local'.我们现在需要向我们的应用程序添加一些秘密和设置。环境变量允许您设置传递给服务器端代码的值。对于开发和测试,我们可以使用dotenv,在应用的根目录下配置环境文件,根据环境命名,例如'.env.development.local'。
danger危险
Care must be taken to avoid storing environment variables in source control.必须注意避免在源代码管理中存储环境变量。
Create or edit .gitignore in the root folder of your application and add the snippet below. This tells git to ignore each of the existing environment files. It also prevents changes to the existing environment files from being stored in git. Make sure you add new environments to .gitignore.在您的应用程序的根文件夹中创建或编辑 .gitignore 并添加以下代码段。这告诉 git 忽略每个现有的环境文件。它还可以防止对现有环境文件的更改存储在 git 中。确保将新环境添加到 .gitignore。
As mentioned in the warning above, add the following lines to '.gitignore':.如上面警告中所述,将以下行添加到“.gitignore”:。
If '.env.development.local' does not exist in your root directory, create it. Otherwise, open it in your code editor and include the following values:如果您的根目录中不存在“.env.development.local”,请创建它。否则,在您的代码编辑器中打开它并包含以下值:
ENVIRONMENT: the environment you are working in which tells dotenv which file to use, e.g. development, test.ENVIRONMENT:你正在工作的环境告诉 dotenv 使用哪个文件,例如开发,测试。
WEBHOOK_SENDER_ADDRESS: a fully qualified address to send notifications from. NOTE: the address must be registered by your Mailchain account. Examples include:WEBHOOK_SENDER_ADDRESS:发送通知的完全限定地址。注意:该地址必须由您的 Mailchain 帐户注册。例子包括:
your mailchain account (username@mailchain.com),您的邮件链帐户 (username@mailchain.com),
an Ethereum address registered in your inbox (0x1234567890123456789012345678901234567890@ethereum.mailchain.com),在您的收件箱中注册的以太坊地址 (0x1234567890123456789012345678901234567890@ethereum.mailchain.com),
an ENS address that resolves to an Ethereum address that is registered to your account (e.g. username.eth@ens.mailchain.com).一个 ENS 地址,该地址解析为在您的帐户中注册的以太坊地址(例如 username.eth@ens.mailchain.com)。
WEBHOOK_RECIPIENT_ADDRESS: the mailchain recipient of messages from the webhook alerts.WEBHOOK_RECIPIENT_ADDRESS:来自 webhook 警报的消息的邮件链收件人。
TENDERLY_SIGNING_KEY: the signing key generated by the webhook in Tenderly.TENDERLY_SIGNING_KEY:Tenderly 中 webhook 生成的签名密钥。
SECRET_RECOVERY_PHRASE: your Mailchain secret recovery phrase for your development account. The same account the WEBHOOK_SENDER_ADDRESS is registered to.SECRET_RECOVERY_PHRASE:您的开发帐户的 Mailchain 秘密恢复短语。 WEBHOOK_SENDER_ADDRESS 注册到的同一帐户。
Install the 'dotenv' package by running the following command in your terminal:通过在终端中运行以下命令来安装“dotenv”包:
npminstall --save dotenv
Insert the following lines at the beginning of 'server.js', above the line const express = require('express');在“server.js”的开头,在 const express = require('express'); 行上方插入以下行
Now replace the following line which will configure the signing key from Tenderly using environment variables in '.env.development.local':现在替换以下行,它将使用“.env.development.local”中的环境变量从 Tenderly 配置签名密钥:
Install the Mailchain SDK by running the following in your terminal:通过在终端中运行以下命令来安装 Mailchain SDK:
npminstall --save @mailchain/sdk
Under the line const app = express(); add the following code snippet to configure the Mailchain SDK:在 const app = express(); 行下添加以下代码片段以配置 Mailchain SDK:
Now we will configure our webhook to call the Mailchain SDK sendMail() function when Tenderly sends TEST webhook calls. (In production, you would want to adjust the message body based on the information expected from contract events or transactions.)现在我们将配置我们的 webhook 以在 Tenderly 发送 TEST webhook 调用时调用 Mailchain SDK sendMail() 函数。 (在生产中,您可能希望根据合约事件或交易的预期信息调整消息正文。)
Add the following to the switch statement:将以下内容添加到 switch 语句中:
switch(eventType){ case'TEST': try{ await mailchain.sendMail({ from: process.env.WEBHOOK_SENDER_ADDRESS, to:[process.env.WEBHOOK_RECIPIENT_ADDRESS], subject:'Webhook Test', content:{ text:`The webhook body:\n${JSON.stringify(body,null,2)}`, html:`<p>The webhook body:</p><pre>${JSON.stringify(body,null,2)}</pre>`, }, }); }catch(error){ thrownewError(error); } break; case'ALERT': // Then define and call a function to handle the alert event break; // ... handle other event types default: console.log('Unhandled event type ', eventType); }
We need the function handling sendMail() to be asynchrous. Update this line: app.post('/webhook', express.raw..., adding async to:我们需要处理 sendMail() 的函数是异步的。更新这一行:app.post('/webhook', express.raw..., 添加异步到:
What can you do now (alerts, use cases etc)?您现在可以做什么(警报、用例等)?
Conclusion结论
Congratulations 🎉 you've built a webhook that can alert you or your users whenever certain events occur on-chain or in transaction logs. There are many use cases, including balance changes, user receipts for NFT purchases, welcome messages, alerting your team of failed transactions, upcoming expiry or liquidation notices and more.恭喜 🎉 你已经构建了一个 webhook,它可以在链上或交易日志中发生某些事件时提醒你或你的用户。有许多用例,包括余额变化、NFT 购买的用户收据、欢迎消息、提醒您的团队交易失败、即将到期或清算通知等等。
The final code for this repository can be found here:这个存储库的最终代码可以在这里找到:
danger危险
Don't forget to disable the webhook in your Tenderly account when you are finished!完成后不要忘记在您的 Tenderly 帐户中禁用网络钩子!
What's next?下一步是什么?
Tenderly provides an important set of tools for Ethereum developers. The ability to simulate, monitor and query transactions and state gives access to a sophisticated set of triggers and alerts. Combining this with web3 communication helps developers provide notifications and updates to users or application developers.Tenderly 为以太坊开发者提供了一套重要的工具。模拟、监控和查询事务和状态的能力允许访问一组复杂的触发器和警报。将此与 web3 通信相结合有助于开发人员向用户或应用程序开发人员提供通知和更新。
Let us know of any interesting variations of this tutorial that you have implemented or if you need any support via our Discord channel.让我们知道您已实现的本教程的任何有趣变体,或者您是否需要通过我们的 Discord 频道获得任何支持。
Mailchain welcomes and greatly appreciates contributions from the community.Mailchain 欢迎并非常感谢社区的贡献。
Mailchain uses various agreements to accept contributions of software code and documentation from individuals, corporations and other entities, and to accept larger grants of existing software products.Mailchain 使用各种协议来接受来自个人、公司和其他实体的软件代码和文档的贡献,并接受对现有软件产品的更大资助。
These agreements help us achieve our goal of providing reliable and long-lived software products through collaborative, open-source software development. In all cases, contributors retain full rights to use their original contributions for any other purpose outside of Mailchain, while providing Mailchain the right to distribute and build upon their work.这些协议帮助我们实现了通过协作、开源软件开发提供可靠和长期使用的软件产品的目标。在所有情况下,贡献者保留将其原始贡献用于 Mailchain 之外的任何其他目的的全部权利,同时向 Mailchain 提供分发和构建其作品的权利。
All contributors of ideas, code, or documentation to Mailchain must complete, agree and sign the agreement via either email or electronic submission.Mailchain 的所有想法、代码或文档的贡献者必须通过电子邮件或电子提交完成、同意并签署协议。
The purpose of the agreement is to clearly define the terms under which intellectual property has been contributed to Mailchain and thereby allow us to defend the project should there be a legal dispute regarding the software. An individual must have submitted a signed ICLA to Mailchain before we give them commit rights to Mailchain.该协议的目的是明确定义将知识产权贡献给 Mailchain 的条款,从而允许我们在软件发生法律纠纷时为项目辩护。在我们授予他们提交 Mailchain 的权利之前,个人必须向 Mailchain 提交签名的 ICLA。
For a corporation or other entity that assigns employees to work on Mailchain, an Entity CLA (ECLA) is available to cover contributing intellectual property via the corporation that may have been assigned as part of an employment agreement.对于指派员工在 Mailchain 上工作的公司或其他实体,实体 CLA (ECLA) 可用于涵盖通过公司贡献的知识产权,这些知识产权可能已作为雇佣协议的一部分被指派。
The ECLA legally binds the corporation or other entity, so a person with authority to enter into legal contracts on behalf of the corporation or other entity must sign it.ECLA 对公司或其他实体具有法律约束力,因此有权代表公司或其他实体签订法律合同的人必须签署它。
The ICLA an individual signs is not tied to any employer they may have, so we recommend that individuals use their personal email addresses in the contact details, rather than their @work addresses.ICLA 个人标志与他们可能拥有的任何雇主无关,因此我们建议个人在联系方式中使用他们的个人电子邮件地址,而不是他们的@work 地址。
Electronic Submission via Github (As Part of a Pull Request)通过 Github 以电子方式提交(作为 Pull Request 的一部分)
When you submit a pull request, Mailchain checks that you have signed an ECLA or ICLA.当您提交拉取请求时,Mailchain 会检查您是否签署了 ECLA 或 ICLA。
If you have not yet signed a CLA, the CLA assistant will add a comment with a link to the Contributor License Agreement (see example image below).如果您尚未签署 CLA,CLA 助手将添加一条评论,其中包含指向贡献者许可协议的链接(参见下面的示例图片)。
Please review and fill in required information, then accept the CLA. (You may need to sign in with Github)请查看并填写必填信息,然后接受 CLA。 (您可能需要使用 Github 登录)
The check in Github should then indicate the CLA has been signed (see example image below).Github 中的支票应该表明 CLA 已经签署(参见下面的示例图片)。
You may sign documents by hand or by electronic signature (e-signature), and submit them by email.您可以手写或通过电子签名(e-signature)签署文件,并通过电子邮件提交。
Signing by hand: When submitting by email, please fill in the form with a PDF viewer, then print and sign it, scan all pages into a single PDF file, and attach the PDF file to an email addressed to support@mailchain.co. 手工签名:通过电子邮件提交时,请使用 PDF 查看器填写表格,然后打印并签名,将所有页面扫描成一个 PDF 文件,并将 PDF 文件附加到电子邮件中,地址为 support@mailchain.co。
If possible, send the attachment from the email address you list in the document. Send only one attached document per email.如果可能,请从您在文档中列出的电子邮件地址发送附件。每封电子邮件仅发送一份附件文件。
E-signature: Please contact support@mailchain.co and request an e-sign CLA, specifying ICLA or ECLA.电子签名:请联系 support@mailchain.co 并请求电子签名 CLA,指定 ICLA 或 ECLA。
Note that typing your name in the field at the bottom of the document is not signing, regardless of the font that you use.请注意,无论您使用何种字体,在文档底部的字段中键入您的姓名都不是签名。
A valid signature involves one of:
Accepting the CLA via the CLA Assistant (Electronic Submission via Github)
Writing your signature by hand on a printed copy of the document
Digitally signing the document by hand-drawing a signature
Signing the document via DocuSign有效签名涉及以下其中一项: 通过 CLA Assistant 接受 CLA(通过 Github 电子提交) 在文档的打印副本上手写签名 通过手绘签名对文档进行数字签名 通过 DocuSign 对文档进行签名
We will not accept unsigned documents.我们不接受未签名的文件。
Mailchain is the communication layer for web3. It makes it possible for people to communicate in a crypto-native way. The platform consists of two parts:Mailchain 是 web3 的通信层。它使人们有可能以加密原生的方式进行交流。该平台由两部分组成:
An open source, multi-chain protocol for sending encrypted messages between blockchain wallet addresses.一种开源的多链协议,用于在区块链钱包地址之间发送加密消息。
A simple, unified inbox application that makes it easy for users to view and send messages using the protocol and to keep track of their on-chain activity.一个简单、统一的收件箱应用程序,使用户可以使用该协议轻松查看和发送消息,并跟踪他们的链上活动。
It's as simple as using email.就像使用电子邮件一样简单。
What problem is Mailchain solving?Mailchain 解决什么问题?
Today, there is no direct way to communicate via blockchain wallet addresses in a crypto-native way. Users are forced to make trade-offs when they link email addresses and lose pseudo-anonymity, or join chat groups for broadcast messages where it's hard to keep track of relevant communication.今天,没有直接的方式以加密原生方式通过区块链钱包地址进行通信。用户在链接电子邮件地址和失去伪匿名性时被迫做出权衡,或者加入难以跟踪相关通信的广播消息的聊天组。
Without communication as a first class citizen, many actions taken for granted on the Internet cannot take place in web3. Users can’t receive direct communications related to their savings, loans, and financial positions. They can’t receive information from projects they care about in the context of how they interact with them. They can’t contact others in their community, for example, to make an offer to purchase a digital collectible. Businesses can’t receive receipts for payments, or invoices. Developers can’t be reached in the event of security issues and can’t send out important communications to their users if there is an issue, upgrade, or decision to be made. Adoption is held back.没有通信作为一等公民,许多在互联网上理所当然的行为是无法在 web3 中发生的。用户无法接收与其储蓄、贷款和财务状况相关的直接通信。在他们如何与他们互动的背景下,他们无法从他们关心的项目中接收信息。例如,他们无法联系社区中的其他人来提出购买数字收藏品的要约。企业无法收到付款收据或发票。如果出现安全问题,则无法联系到开发人员,如果有问题、升级或需要做出决定,也无法向用户发送重要信息。采用被阻止。
Mailchain acts as your web3 inbox, receiving messages in the context of your identities. Digital art-related messages get sent to your digital collector identity, gaming-related notifications get sent to your gaming identity, and DeFi notifications get sent to your DeFi identity. Mailchain gives you the power to communicate and maintain privacy at the same time.Mailchain 充当您的 web3 收件箱,在您的身份上下文中接收消息。与数字艺术相关的消息会发送到您的数字收藏家身份,与游戏相关的通知会发送到您的游戏身份,而 DeFi 通知会发送到您的 DeFi 身份。 Mailchain 使您能够同时进行通信和维护隐私。
How much does it cost to send a message on Mailchain?在 Mailchain 上发送消息需要多少费用?
Mailchain’s economic model is designed to be sustainable. It provides a "public good" quota of free messages for human users ensuring anyone can have access to secure, private communication at no cost. The model also supports the protocol and its infrastructure providers through message fees for high volume senders. Fees are targeted to be below $0.005.Mailchain 的经济模型旨在实现可持续发展。它为人类用户提供了“公益”配额的免费消息,确保任何人都可以免费访问安全、私密的通信。该模型还通过向大容量发送者收取消息费用来支持该协议及其基础设施提供商。费用目标是低于 0.005 美元。
Can I send a message to or receive email from a traditional email address?我可以向传统电子邮件地址发送消息或从传统电子邮件地址接收电子邮件吗?
Not yet. Mailchain is a web3 communication protocol that works with web3 identities (e.g. blockchain wallet addresses and names), guaranteeing end-to-end encryption and verified sender origin. It does not support sending messages to or from traditional email. There is an open feature request here https://go.mailchain.com/feat-traditional-email. We'd love to hear your thoughts on this.还没有。 Mailchain 是一种 web3 通信协议,它与 web3 身份(例如区块链钱包地址和名称)一起工作,保证端到端加密和验证发件人来源。它不支持向传统电子邮件发送消息或从传统电子邮件发送消息。这里有一个开放的功能请求 https://go.mailchain.com/feat-traditional-email。我们很想听听您对此的看法。
Why has Mailchain developed its own protocol?为什么 Mailchain 开发了自己的协议?
There is no purpose-built communication protocol that supports group or one-to-one, end-to-end encrypted messaging between web3 identities.没有专门构建的通信协议支持 web3 身份之间的组或一对一、端到端加密消息传递。
There are big challenges related to using other protocols. Constraints include scalability, security, and price volatility challenges.使用其他协议存在很大的挑战。约束包括可扩展性、安全性和价格波动挑战。
Mailchain's protocol is purpose built for secure and private communication. It natively handles encryption, addressing, key lookups, transport, and storage.Mailchain 的协议专为安全和私密的通信而构建。它本机处理加密、寻址、密钥查找、传输和存储。
Will Mailchain be fully decentralized?Mailchain 会完全去中心化吗?
Yes. Mailchain will be progressively decentralized. Our initial priorities are user experience, security, and supporting user-owned identity and data. Mailchain will then decentralize its protocol functions with an incentivization structure that encourages members of the community to participate in running infrastructure.是的。 Mailchain 将逐步去中心化。我们最初的优先事项是用户体验、安全性以及支持用户拥有的身份和数据。然后,Mailchain 将通过鼓励社区成员参与运行基础设施的激励结构来分散其协议功能。
Can someone run their own Mailchain infrastructure?有人可以运行自己的 Mailchain 基础设施吗?
As protocol functions are decentralized, anyone will be able to run their own Mailchain infrastructure.由于协议功能是去中心化的,任何人都可以运行自己的 Mailchain 基础设施。
Why would someone run Mailchain infrastructure?为什么有人会运行 Mailchain 基础设施?
Businesses may want to run their own infrastructure to control how and where messages are stored. Other community members or service providers may run infrastructure in order to receive rewards.企业可能希望运行自己的基础架构来控制消息的存储方式和存储位置。其他社区成员或服务提供商可能会运行基础设施以获得奖励。
A Secret Recovery Phrase, sometimes known as a "mnemonic seed phrase" is used to mathematically derive all the messaging keys, private keys, signatures and other secrets for your account.秘密恢复短语,有时称为“助记种子短语”,用于从数学上推导出您帐户的所有消息传递密钥、私钥、签名和其他秘密。
It should never be shared with anyone because doing so would give full, irrevocable access to your account. A Secret Recovery Phrase cannot be changed or recovered.永远不要与任何人共享它,因为这样做会提供对您帐户的完全、不可撤销的访问权限。秘密恢复短语无法更改或恢复。
Who can access my account information?谁可以访问我的帐户信息?
Only you are able to access your account information and data using your Secret Recovery Phrase or account password. Mailchain cannot access your account or account information.只有您可以使用您的秘密恢复短语或帐户密码访问您的帐户信息和数据。 Mailchain 无法访问您的帐户或帐户信息。
What happens if I forget or lose my password?如果我忘记或丢失密码怎么办?
If you forget or lose your password, you can recover your account using your Secret Recovery Phrase.如果您忘记或丢失了密码,您可以使用您的秘密恢复短语恢复您的帐户。
What happens if I forget or lose my Secret Recovery Phrase?如果我忘记或丢失了我的秘密助记词怎么办?
If you forget or lose your Secret Recovery Phrase, you can recover your account if you know your Mailchain username and password.如果您忘记或丢失了您的 Secret Recovery Phrase,如果您知道您的 Mailchain 用户名和密码,则可以恢复您的帐户。
What happens if I forget my Secret Recovery Phrase and my password?如果我忘记了我的秘密助记词和密码会怎样?
If you forget your Secret Recovery Phrase and your password, your account will be inaccessible.如果您忘记了您的秘密恢复短语和密码,您的帐户将无法访问。
Will my data be accessible after I have recovered my account?恢复帐户后我的数据可以访问吗?
When you log in to Mailchain with your Secret Recovery Phrase or username and password combination, your messages, registered wallets, settings, etc. will be accessible to you.当您使用您的秘密恢复短语或用户名和密码组合登录 Mailchain 时,您将可以访问您的消息、注册的钱包、设置等。
What should I do if I suspect my Secret Recovery Phrase or username and password combination have been compromised?如果我怀疑我的秘密助记词或用户名和密码组合已被泄露,我该怎么办?
Any user who suspects their Secret Recovery Phrase or username and password combination has been compromised should create a new account and migrate their blockchain addresses by re-registering them with the new account. Any new messages will now use the messaging keys for the new account.任何怀疑其 Secret Recovery Phrase 或用户名和密码组合已被泄露的用户都应创建一个新帐户并通过使用新帐户重新注册来迁移其区块链地址。任何新消息现在都将使用新帐户的消息密钥。
Mailchain messages are encrypted end-to-end. This means that once the sender has encrypted a message using the recipient's encryption key, only the recipient is able to decrypt it. The sender also keeps an encrypted version of the message.邮件链消息是端到端加密的。这意味着一旦发件人使用收件人的加密密钥加密了消息,只有收件人能够解密它。发件人还保留消息的加密版本。
Mailchain cannot read your messages, the storage provider cannot read your messages, your internet service provider cannot read your messages.Mailchain 无法读取您的消息,存储提供商无法读取您的消息,您的互联网服务提供商无法读取您的消息。
Mailchain stores encrypted message data on IPFS and other distributed object stores.Mailchain 在 IPFS 和其他分布式对象存储上存储加密的消息数据。
Are my messages stored on the blockchain?我的消息存储在区块链上吗?
No. When a message is sent, the message is encrypted and stored on distributed storage. An encrypted "delivery request", which contains information for the message recipient to be able to collect their encrypted message, is sent as a blockchain transaction. Once a message has been collected, it will be stored in the recipient's inbox, and can be removed from the distributed storage location.不会。发送消息时,消息会被加密并存储在分布式存储中。加密的“交付请求”作为区块链交易发送,其中包含消息接收者能够收集其加密消息的信息。收集到消息后,它将存储在收件人的收件箱中,并且可以从分布式存储位置中删除。
To contact us for support, please use any one of the following methods:要联系我们寻求支持,请使用以下任一方法:
Send us a mailchain message or email to support@mailchain.com向我们发送邮件链消息或电子邮件至 support@mailchain.com
Log a ticket via https://support.mailchain.com (requires email address)通过 https://support.mailchain.com 登录票证(需要电子邮件地址)
Contact us in our Discord support channel: https://discord.gg/dS45WHwYEn (requires using Discord)通过我们的 Discord 支持渠道联系我们:https://discord.gg/dS45WHwYEn(需要使用 Discord)
danger危险
Remember we will never ask you for any sensitive information, or your Secret Recovery Phrase, or your password, and we will never contact you first to request you give us any information or carry out any actions. If someone asks you for this, please report it to our support team.请记住,我们绝不会要求您提供任何敏感信息、您的秘密恢复短语或您的密码,我们也绝不会首先与您联系以要求您向我们提供任何信息或执行任何操作。如果有人要求您这样做,请向我们的支持团队报告。